Inconsistent Execution Order of setImmediate and setTimeout(0) in Node.js

29 views Asked by At

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
1

There are 1 answers

0
IndevSmiles On

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:

NodeJS Event Loop Diagram (Source: https://nodejs.org/en/learn/asynchronous-work/event-loop-timers-and-nexttick)

setTimeout is scheduled during the timers phase, though actual execution happens at the beginning of the poll phase.

setImmediate executes in the check phase when the poll phase becomes idle. setImmediate is supposed to be delayed until after the event queue is empty.

setImmediate ALWAYS happens second because they're executed in a different step.