Skip to content

Instantly share code, notes, and snippets.

@joergpatz
Last active April 16, 2021 12:19
Show Gist options
  • Save joergpatz/880d0d978d5f66ecb233b5b996b713f5 to your computer and use it in GitHub Desktop.
Save joergpatz/880d0d978d5f66ecb233b5b996b713f5 to your computer and use it in GitHub Desktop.
Node.js Eventloop Timers and NextTick
/**
* nextTick vs setImmediate, visual explanation
*
* https://stackoverflow.com/questions/17502948/nexttick-vs-setimmediate-visual-explanation
* https://nodejs.dev/learn/understanding-process-nexttick
*/
// SETIMMEDIATE
setImmediate(function A() {
setImmediate(function B() {
log(1);
setImmediate(function D() { log(2); });
setImmediate(function E() { log(3); });
});
setImmediate(function C() {
log(4);
setImmediate(function F() { log(5); });
setImmediate(function G() { log(6); });
});
});
setTimeout(function timeout() {
console.log('TIMEOUT FIRED');
}, 0)
// 'TIMEOUT FIRED' 1 4 2 3 5 6
// OR
// 1 'TIMEOUT FIRED' 4 2 3 5 6
// NEXTTICK
process.nextTick(function A() {
process.nextTick(function B() {
log(1);
process.nextTick(function D() { log(2); });
process.nextTick(function E() { log(3); });
});
process.nextTick(function C() {
log(4);
process.nextTick(function F() { log(5); });
process.nextTick(function G() { log(6); });
});
});
setTimeout(function timeout() {
console.log('TIMEOUT FIRED');
}, 0)
// 1 4 2 3 5 6 'TIMEOUT FIRED'
/**
* The only real difference is that multiple nextTick may fire in one loop iteration (depending on maxTickDepth),
* while setImmediate fires once per iteration.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment