Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript setInterval - rate or delay?

Does the Javascript setInterval method wait (at least) the specified interval between two executions of the specific code, or does it wait that interval in between finishing the previous execution and the beginning of the next execution?

(or, when comparing to Java's ScheduledExecutorService methods - is setInterval similar to scheduleAtFixedRate() or rather scheduleWithFixedDelay()?)

like image 668
user976850 Avatar asked Jul 10 '12 07:07

user976850


1 Answers

If you call setInterval with 1000 milliseconds interval and callback code takes 100 milliseconds to run, next callback will be executed after 900 milliseconds.

If callback takes 1050 milliseconds, the next one will fire up immediately after the first one finishes (with 50 milliseconds delay). This delay will keep accumulating.

So in Java world this is similar to scheduleAtFixedRate(). If you need scheduleWithFixedDelay() behaviour, you must use setTimeout() and reschedule callback each time it finishes:

function callback() {
    //long running code
    setTimeout(callback, 1000);
}
setTimeout(callback, 1000);

The code above will wait exactly 1000 milliseconds after callback() finished before starting it again, no matter how long it took to run.

like image 172
Tomasz Nurkiewicz Avatar answered Oct 04 '22 12:10

Tomasz Nurkiewicz