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…

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

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

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.