Event loop primer

19 October 2011

I recently got into developing a web application with node.js (aka cancer).
Coming from a synchronous world, it took (and to be honest, still takes)
quite a while to grok how writing asynchronous code differs from my
previous experiences (AJAX calls with jQuery only go that far).

As with many fine technologies or methods (TDD, NoSQL, functional
programming come to mind) it’s your whole
thinking that has to change. In this post I want to share an example
from Trevor Burnham’s excellent Coffeescript book that gave me one
of those aha moments.

(If you don’t read Coffeescript code, you can go to the Coffeescript web site
and paste the above example in to get compiled Javascript)

The example above is broken. It gets stuck at the until countdown is 0
row. In an event loop system events (callbacks) only get run after the “main line”
of execution (or, in other words, all other code) has completed.
So the until loop blocks out the callback of the setInterval,
countdown never gets decremented and thus an endless loop ensues.

I’m sure that there are many ways to fix this, I came up with the
following (and wonder if there is one closer to the original):