From this page you can share How JavaScript Timers Work to a social bookmarking site or email a link to the page.
Social WebE-mail
Enter multiple addresses on separate lines or separate them with commas.
How JavaScript Timers Work
(Your Name) has forwarded a page to you from Ajaxonomy
(Your Name) thought you would like to see this page from the Ajaxonomy web site.

How JavaScript Timers Work


John Resig has posted a very interesting excerpt on JavaScript timers from his upcoming book, Secrets of the JavaScript Ninja, due out this fall. In his post, John covers timer delay and asynchronous events on a single thread, including three functions associated with timers and the differences between each:

  • var id = setTimeout(fn, delay); - Initiates a single timer which will call the specified function after the delay. The function returns a unique ID with which the timer can be canceled at a later time.
  • var id = setInterval(fn, delay); - Similar to setTimeout but continually calls the function (with a delay every time) until it is canceled.
  • clearInterval(id); - Accepts a timer ID (returned by either of the aforementioned functions) and stops the timer callback from occurring.

Here's a quick summary of the key points of the post:

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

Read the full post for more detail on these key points and to better understand how JavaScript timers work.