Are recursive setTimeouts bad for performance?

Viewed 520

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
}
3 Answers

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.

Since the browser is supposed to do nothing at all for another 2 seconds anyway, any hypothetical overhead of recursive setTimeout() compared to setInterval() can safely be ignored. But your program might be harder to understand when you use setTimeout() to exactly emulate setInterval(). For that reason, I would rather use setInterval to do that slideshow.

That said, in certain applications on node.js, I experienced that setInterval() has a little drift, so using setTimeout() leads to a more exact timing. But in the use case of the slide show, a little drift of a few milliseconds per interval can be ignored.

When setTimeout is called, the JS runtime schedule the execution of the specified callback. It's not a recursion since we don't wait for the callback return value.

Try to see setTimeout simply like something that fill a schedule, basically a setter. If you call setTimeout(callback, 2000) at 8:00:00AM, the JS runtime could say to you: "Ok! I'll execute that callback at 8:00:02 AM, but I can still do other things while waiting."

Hope this was helpful.

Related