Monday, February 25th, 2008
How JavaScript Timers Work
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:
- 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 thesetInterval
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
andsetInterval
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).





…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…
JavaScript does not have timers. What John is describing is the DOM’s timers.
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.