Hacker Newsnew | past | comments | ask | show | jobs | submitlogin
How JavaScript Timers Work (ejohn.org)
72 points by shawndumas on April 25, 2011 | hide | past | favorite | 6 comments


Almost every software timer follows this rule (even ones in the kernel) - "Interval timers / Thread Sleep guarantee that the amount of time waited is at least this long, it doesn't guarantee that it is exactly this long.

As seanalltogether mentions, timers are run at the beginning of the render loop => "Run timers, layout page, render page, repeat". If you're busy doing stuff in #2 or #3 (or if your timer handler takes forever), you're not running #1.


Unless, of course, you are running a hard real-time OS, in which case kernel timers are guaranteed to fire at the exact rate specified.


This is where I defer to the "almost" :)


Similar to many gui frameworks you have a run loop that processes an event pool and a render sequence over and over and over. Events are queued and dispatched into the event pool as the browser receives them, followed by dom updates being processed in the render step. However this isn't always true and many javascript code blocks can force an immediate render(Text is deferred, canvas is immediate, not sure about css).

For this reason your event pool can be delayed significantly while waiting for rendering to complete.


css causes immediate renders but does occasionally batch changes (I think opera was the best at that)

Its inconsistent implementation meant you really are best doing any style modifications off the dom and then reattaching when complete


I believe this is commonly called the 'Reactor pattern':

http://en.wikipedia.org/wiki/Reactor_pattern




Consider applying for YC's Summer 2026 batch! Applications are open till May 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: