As explained on the official guides (https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#setimmediate-vs-settimeout), if I run the following snippet, I get different order for logs, sometimes immediate first, and sometimes timeout first, i.e. the order is non-deterministic:
setImmediate(() => {
console.log("immediate");
});
setTimeout(() => {
console.log("timeout");
}, 0);
Output:
> node index.js
immediate
timeout
> node index.js
immediate
timeout
> node index.js
timeout
immediate
However, if I add the process.nextTick() call to the mix, unexpectedly, the order for timeout and immediate is fixed (timeout is always printed before immediate):
setImmediate(() => {
console.log("immediate");
});
setTimeout(() => {
console.log("timeout");
}, 0);
process.nextTick(() => {
console.log("next tick");
});
Output:
> node index.js
next tick
timeout
immediate
> node index.js
next tick
timeout
immediate
> node index.js
next tick
timeout
immediate
I could not understand how does process.nextTick() affect the order of timeout and immediate. Can someone help me understand what is happening internally here?