I've noticed a seemingly inconsistent behavior regarding the execution order of setImmediate and setTimeout with a delay of 0 milliseconds in Node.js
setImmediate(() => {
console.log('setImmediate callback');
});
setTimeout(() => {
console.log('setTimeout callback');
}, 0);
console.log('This code runs first.');
i got this answer-
This code runs first.
setTimeout callback
setImmediate callback
but some times its changing,why? like,
This code runs first.
setImmediate callback
setTimeout callback
There is no such inconsistency. The code provided will always result in the first example. To understand why I say this so confidently (other than that I ran the provided code 10 thousand times to prove it to myself), you need to have an understanding on how NodeJS handles the event loop. Please refer to this diagram:
setTimeoutis scheduled during the timers phase, though actual execution happens at the beginning of the poll phase.setImmediateexecutes in the check phase when the poll phase becomes idle.setImmediateis supposed to be delayed until after the event queue is empty.setImmediateALWAYS happens second because they're executed in a different step.