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()
?)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With