Search code examples
javascriptrecursionsettimeout

Are recursive setTimeouts bad for performance?


I created an image slideshow following this tutorial by W3Schools: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_slideshow_auto

It uses a recursive function via setTimeout() to auto-slide the images. Is this bad for the user's browser performance? Or can I use it without worrying?

var slideIndex = 0;
showSlides();

function showSlides() {
  var i;
  var slides = document.getElementsByClassName("mySlides");
  var dots = document.getElementsByClassName("dot");
  for (i = 0; i < slides.length; i++) {
    slides[i].style.display = "none";
  }
  slideIndex++;
  if (slideIndex > slides.length) {
    slideIndex = 1
  }
  for (i = 0; i < dots.length; i++) {
    dots[i].className = dots[i].className.replace(" active", "");
  }
  slides[slideIndex - 1].style.display = "block";
  dots[slideIndex - 1].className += " active";
  setTimeout(showSlides, 2000); // Change image every 2 seconds
}

Solution

  • If by recursive, you mean a setTimeout that ends up calling another (or more commonly itself), then nope.

    In fact, that is the preferred way to go about it.

    By using setTimeout it gives the browser a break in between updates to make other updates (a.k.a., it is "non-blocking").

    You can alternatively use a setInterval and let that run, but the problem with that is if something goes wrong, you have to explicitly call clearInterval or else it'll just keep throwing errors.

    setTimeout will only throw one error and stop (since it doesn't make it to the call to make another setTimeout). setTimeout is definitely my, and many others, preferred method.

    It also won't create any sort of stack overflow (like normal recursive functions can if they recurse too long) because it isn't truly recursive in that sense.