Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setInterval and long running functions

How does setInterval handle callback functions that take longer than the desired interval?

I've read that the callback may receive the number of milliseconds late as its first argument, but I was unable to find why it would be late (jitter, or long running functions).

And the wonderful follow up, does it behave differently for the common browsers?

like image 259
Allain Lalonde Avatar asked Dec 29 '09 19:12

Allain Lalonde


People also ask

How does setInterval affect performance?

This is unlikely to make much of a difference though, and as has been mentioned, using setInterval with long intervals (a second is big, 4ms is small) is unlikely to have any major effects.

Does setInterval call function immediately?

Method 1: Calling the function once before executing setInterval: The function can simply be invoked once before using the setInterval function. This will execute the function once immediately and then the setInterval() function can be set with the required callback.

What is difference between setInterval and setTimeout?

setTimeout allows us to run a function once after the interval of time. setInterval allows us to run a function repeatedly, starting after the interval of time, then repeating continuously at that interval.

How long does setInterval last?

When your code calls the function repeatEverySecond it will run setInterval . setInterval will run the function sendMessage every second (1000 ms).


1 Answers

Let me quote an excellent article about timers by John Resig:

setTimeout(function(){
  /* Some long block of code... */
  setTimeout(arguments.callee, 10);
}, 10);

setInterval(function(){
  /* Some long block of code... */
}, 10);

These two pieces of code may appear to be functionally equivalent, at first glance, but they are not. Notably the setTimeout code will always have at least a 10ms delay after the previous callback execution (it may end up being more, but never less) whereas the setInterval will attempt to execute a callback every 10ms regardless of when the last callback was executed.

Intervals may execute back-to-back with no delay if they take long enough to execute (longer than the specified delay).

like image 97
Christian C. Salvadó Avatar answered Oct 22 '22 00:10

Christian C. Salvadó