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.
1 2 3 4 5 6 7 countdown = 10 h = setInterval -> countdown-- , 100 do (->) until countdown is 0 clearInterval h console.log 'Surprise!'
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):
1 2 3 4 5 6 7 countdown = 10 h = setInterval -> countdown-- if countdown is 0 console.log 'Surprise' clearInterval h , 100
And that’s it. I hope this simple example pushes you up on that pesky learning curve.
(The snippet was published by the kind permission of the author.)