18

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?

Allain Lalonde
  • 91,574
  • 70
  • 187
  • 238
  • Good question. I would suspect the answer is browser specific. Should we run some tests to find out? –  Dec 29 '09 at 19:29
  • I wouldn't rely on receiving any arguments to the callback. Instead, use a simple Date comparison. That seems the most reliable and cross-browser approach to me. – Roman Nurik Dec 29 '09 at 19:35

1 Answers1

25

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).

Community
  • 1
  • 1
Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
  • 8
    So, in a nutshell, because JavaScript threading is all single threaded, the callbacks cannot be running in parallel. Perfect. – Allain Lalonde Dec 29 '09 at 19:59