How JavaScript Timers Work

Written by on February 25th, 2008 in Ajax News.

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:

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

Source: Ajaxian
Original Article: http://feeds.feedburner.com/~r/ajaxian/~3/240845499/how-javascript-timers-work

Comments are closed.



Site Navigation