Sitemap
Develoger

In the beginning there was a bug in the code, literally.

Follow publication

setTimeout VS setInterval

--

Zoom image will be displayed
People aren’t only one who need to wait in queue…

Intro

First of all, we need to be aware that this topic is somehow opinionated. Still what I want to show is pretty much a fact and like everything that I write about it’s rooted in my personal experience.

Additionally it’s important to know that this article shouldn’t be related to window.requestAnimationFrame(); Even if there are use-cases where that particular API can (should) be used instead setTimeout || setInterval, it’s highly coupled with DOM repaint, which ideally can happen 60 times per second. Thus, control over how often some code should be executed is limited.

window.onload

Few days ago a friend of mine asked me:

What do you think about timers?

To be honest I instantly recalled the pain… I mean when you work for some time in this industry, you actually can associate vast majority of situations with your personal experience.

When I was young and in Mr stupid phase, one guy who I disliked said to me something like:

Never set timer that will execute your code. Instead listen what machine have to say and react when something change.

I was like, oh yeah and then I left the room. Immediately forgetting what he stated. Since you know I didn’t like the guy…

Yeah that was me on the peak of Mt. Stupid. Proud and earless.

Timers are not bad

I dare you to implement a clock without some sort of timer.

Timers are just misused. Like most of the stuff anyway.
When you look at some codebase, you will not see syntax, nor limitations of some programming language. Instead you will see how developer that wrote it thinks.

Good thing is that 99% of Front-End engineers already know what is better than timer and when to use that particular thing.

window.onload = () => {
// see, here you waited for signal from the browser
};

setInterval

Well, I must say that intervals were my thing back in the day.
Whenever I needed to do something periodically I would go with the setInterval(); // That worked fine, until it turned into hell

Some facts

Once you set interval, it will continue to exist as a process until you clear it, or your current session ends.

setInterval guarantees that your code will be passed to STACK in exact intervals. This means that period of time between each interval will always be the same. *

Wait but does that mean that my code will be executed in the same manner?

No. That just means that setInterval API will put your function to the STACK. Will it be executed immediately, depends on many factors. But in general there will always be some delay.

JavaScript apps live and work within the browser, which means that setInterval delay increments with time (or just varies). There are few main reasons for such behavior…

  1. Hardware limitations of devices which run our apps
  2. Leaving our app to run in inactive tab of browser
  3. Overall codebase that isn’t optimized

All of the mentioned can result in situation described on the image below.

Zoom image will be displayed
Funky stuff is happening there…

Execution of dummyMethod1() took longer than expected, due to the reason unknown. Therefore, because of the nature of JavaScript event loop it got stuck on the STACK. That means other methods will need to wait in order to be executed…

Remember when I said?
“That worked fine, until it turned into hell”

Now our clockTimer method will be executed 3 times (quite possibly even more) in interval that we actually can’t control (or we kind of can if we don’t write that awful dummyMethod1()) . All that happen because of… Timers.
Additionally setInterval have no clue what it delivers to STACK.
It’s job is to send it at specified moment and that’s it.

In the ideal environment setInterval sounds awesome.
In browser and with JavaScript in mind, not so cool (most of the time).

* now you see what I meant there (setInterval guarantees that your code will be passed to STACK in exact intervals). Actual time of execution of your code have nothing with setInterval.

setTimeout

If you don’t know what is recursion and how to implement it in JavaScript, now is the perfect time to checkout: What is recursion? (still I would prefer if you keep on reading this one).

Using setTimeout is like calling setInterval once

Obviously we can use setTimeout to postpone execution of some code to another time. But what happens if we want to execute some code in intervals. I mean we did start with setInterval with a reason.

In that case you should go with recursive setTimeout. It still can’t guarantee that your code will be executed in exact intervals (because of same issues that I pointed out to when I wrote about setInterval). But it will never produce such scenario where you have multiple occurrences of same method on STACK.

When you implement recursion together with setTimeout, you will get setInterval, just better.

Zoom image will be displayed

In this scenario, decision for delivering clockTimer() to STACK isn’t handled with setTimeout (like it’s the case with setInterval). Instead it is quite opposite.
With implementation of recursive setTimeout, clockTimer itself is responsible for next call of the function. setTimeout is there just to delay it’s next execution. Thus creating interval.

That way we are sure that next call, or better say, next placement of the method to the STACK will be done exactly 1000ms (in this example) after current execution of the method.

Using recursive setTimeout guarantees that until our method gets fully executed it will never be sent for another execution.

Which obviously can and most probably will happen when we use setInterval.

Outro

At the end I would like to point out that this article was not meant to show setInterval as ultimate bad choice.
What you need to know, is to understand how it works, which will help you in future debugging and overall decision making.

If you are reading this it means that you are curious and passionated about JavaScript and Front-End in general. That makes two of us!
Consider joining me on this adventure of discover by following me here, maybe clicking that heart or checkout my twitter account https://twitter.com/develoger

Once I hit 1000 followers on the blog I will share the prizes (public draw) -- 2 yearly subscriptions to https://egghead.io

--

--

Develoger
Develoger

Published in Develoger

In the beginning there was a bug in the code, literally.

Develoger
Develoger

Written by Develoger

Don’t worry, it’s safe outside of your comfort zone...

Responses (2)