Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Great examples to understand the differences of setImmediate, setTimeout and nextTick()
/**
* setImmediate callbacks are fired off the event loop, once per iteration in the order that they were queued.
* So on the first iteration of the event loop, callback A is fired.
* Then on the second iteration of the event loop, callback B is fired, then on the third iteration of the event loop callback C is fired, etc.
* This prevents the event loop from being blocked and allows other I/O or timer callbacks to be called in the mean time (as is the case of the 0ms timeout, which is fired on the 1st or 2nd loop iteration).
*/
setImmediate(function A() {
setImmediate(function B() {
console.log(1);
setImmediate(function D() { console.log(2); });
setImmediate(function E() { console.log(3); });
});
setImmediate(function C() {
console.log(4);
setImmediate(function F() { console.log(5); });
setImmediate(function G() { console.log(6); });
});
});
setTimeout(function timeout() {
console.log('TIMEOUT FIRED');
}, 0)
/**
* nextTick callbacks, however, are always fired immediately after the current code is done executing and BEFORE going back to the event loop.
* In the nextTick example, we end up executing all the nextTick callbacks before ever returning to the event loop.
* Since setTimeout's callback will be called from the event loop, the text 'TIMEOUT FIRED' will not be output until we're done with every nextTick callback.
* Thats one of the reason why you should never call nextTick recursively if you want to process IO operations.
*/
process.nextTick(function A() {
process.nextTick(function B() {
console.log(1);
process.nextTick(function D() { console.log(2); });
process.nextTick(function E() { console.log(3); });
});
process.nextTick(function C() {
console.log(4);
process.nextTick(function F() { console.log(5); });
process.nextTick(function G() { console.log(6); });
});
});
setTimeout(function timeout() {
console.log('TIMEOUT FIRED');
}, 0)
/**
* setTimeout is simply like calling the function after delay has finished. Whenever a function is called it is not executed immediately,
* but queued so that it is executed after all the executing and currently queued eventhandlers finish first.
* setTimeout(,0) essentially means execute after all current functions in the present queue get executed. No guarantees can be made about how long it could take.
*/
setTimeout(function A() {
setTimeout(function B() {
console.log(1);
setTimeout(function D() { console.log(2); });
setTimeout(function E() { console.log(3); });
});
setTimeout(function C() {
console.log(4);
setTimeout(function F() { console.log(5); });
setTimeout(function G() { console.log(6); });
});
});
setTimeout(function timeout() {
console.log('TIMEOUT FIRED');
}, 0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment