I am struggling to think of a use case in web-application development that needs to use setInterval
.
The "danger" with setInterval
being that it just queues up callbacks should one not complete within the allocated interval.
Furthermore, the behaviour of setInterval
can be simulated with setTimeout
or requestAnimationFrame
without this "danger".
Given this, can someone provide me with a use-case where setInterval
is the superior/more appropriate option?
Edit:
Thought I'd jot down my findings.
setInterval
is an easy way to have something run at even-ish intervals. The intervals will mainly be quite accurate, but if the event loop is blocked, then they might be completely inaccurate.
var x = 0;
setInterval(function() {
waitBlocking(5000);
document.write(x++);
},100);
function waitBlocking(ms) {
var start = Date.now();
while((Date.now() - start) < ms) {}
}
As far as I can tell, setInterval
is useful not if you want evenly spread interval callback invocations (see above), but if you want a convenient way of having a specific number of callback invocations in a period, spread across the timeframe as close as possible to when they should have run. Which seems like a rather narrow use case.
I'm sure I am missing something.
Edit 2:
This is basically the best approximation of a clock JS can achieve, so I guess setInterval
is the "clock timer". Presumably this was useful in applications that needed simple clocks.