How JavaScript Timers Work
Date : 2008 02 25 Category : Tech & DevelopmentIt 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:
PLAIN TEXT JAVASCRIPT: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.
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).