Created
January 10, 2012 17:27
-
-
Save csosborn/1590128 to your computer and use it in GitHub Desktop.
illustration of timer-related event loop problem in Node.js 0.6
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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