Monday, February 25th, 2008

How JavaScript Timers Work

Category: JavaScript

It is so great that John is blogging concepts from his upcoming book before it goes out. What a treat for us, and hopefully great marketing for his book!

In How JavaScript Timers Work, John takes us through the actual mechanics of setInterval and setTimeout:

This enables us to grok the difference between:


  1. setTimeout(function(){
  2.     /* Some long block of code... */
  3.     setTimeout(arguments.callee, 10);
  4.   }, 10);
  6.   setInterval(function(){
  7.     /* Some long block of code... */
  8.   }, 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.

There’s a lot that we’ve learned here, let’s recap:

  • JavaScript engines only have a single thread, forcing asynchronous events to queue waiting for execution.
  • setTimeout and setInterval are fundamentally different in how they execute asynchronous code.
  • If a timer is blocked from immediately executing it will be delayed until the next possible point of execution (which will be longer than the desired delay).
  • Intervals may execute back-to-back with no delay if they take long enough to execute (longer than the specified delay).

Posted by Dion Almaer at 7:03 am

4 rating from 31 votes


Comments feed TrackBack URI

…lot of investigations and work going on lately with regard to timers… John has had a few posts and likewise the Gears 0.2 release had some timer pieces…

Comment by Mark Holton — February 25, 2008

JavaScript does not have timers. What John is describing is the DOM’s timers.

Comment by crock — February 26, 2008

The article could have been better if it had talked about the internals other than a black box model investigation (although I understand that each browser is different — one internal is better than no internal).

Wouldn’t hurt to have a comparison to ECMAScript4 timers as well.

@Brendan Eich, any chance I can forward you some notes on Linux Kernel Scheduler and Timers? I know it’s too late for ES4, but the timers *need* a lot of work.

I suppose I can always write up a JS equivalent to the Linux kernel scheduler and timer for a prototype.

Comment by ibolmo — February 27, 2008

Leave a comment

You must be logged in to post a comment.