setTimeout / setInterval and Ensuring Time Gaps

Posted on 08/02/2008 @ 08:03PM

After coming across an informative post by John Resig about how Javascript timers work, I had to copy a useful code snippet from him.See the following:

  setInterval(function(){
    doSomething();
  }, 10);

Due to the way Javascript queues the execution of the timed code, it's possible for one execution to get delayed while the following execution fires on time. Thus doSomething() could fire twice without a 10ms gap in between.

His other bit of code could be very useful in situations where you need that time gap to be ensured:

  setTimeout(function(){
    doSomething();
    setTimeout(arguments.callee, 10);
  }, 10);

This forces there to be a minimum of 10ms between calls. The time gap may sometimes be longer than 10ms, but never less.