Skip to content

Instantly share code, notes, and snippets.

@csosborn
Created January 10, 2012 17:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save csosborn/1590128 to your computer and use it in GitHub Desktop.
Save csosborn/1590128 to your computer and use it in GitHub Desktop.
illustration of timer-related event loop problem in Node.js 0.6
var i = 0;
// complain loudly if node exits before this handler is removed
var onExit = function() {
console.log('Exiting prematurely! (after %s iterations)', i);
};
process.on('exit', onExit);
function doIteration() {
if (i < 100) {
i++;
// set a timeout
var to = setTimeout(function() {
console.log('timed out');
// set another timeout.
// (IMPORTANT! without this second setTimeout the problem goes away)
to = setTimeout(function() {
to = null;
console.log('timed out again');
}, 2);
}, 2);
// for each iteration, wait 5ms, clear the timeout if it is still active,
// then call doIteration again
setTimeout(function() {
if (to) {
// without this clearTimeout the problem goes away
console.log('clearing timeout');
clearTimeout(to);
}
doIteration();
}, 5);
}
else {
process.removeListener('exit', onExit);
console.log('exiting properly after %s iterations', i);
}
}
doIteration();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment