According to the node.js docs about event loop:
Each phase has a FIFO queue of callbacks to execute. While each phase is special in its own way, generally, when the event loop enters a given phase, it will perform any operations specific to that phase, then execute callbacks in that phase’s queue until the queue has been exhausted or the maximum number of callbacks has executed. When the queue has been exhausted or the callback limit is reached, the event loop will move to the next phase, and so on.
Consider the following piece of code:
setImmediate(() => {
console.log("setImmediate 1");
setImmediate(() => {
console.log("setImmediate 2");
});
});
setTimeout(() => {
console.log("setTimeout 1");
}, 2);
setImmediate(() => {
console.log("setImmediate 3");
}, 0);
The actual output is
setImmediate 1
setImmediate 3
setTimeout 1
setImmediate 2
But I would expect it to be
setImmediate 1
setImmediate 3
setImmediate 2
setTimeout 1
My reasoning:
- Schedule
setImmediate
for"setImmediate 1"
(Check queue:["setImmediate 1"]
). - Schedule
setTimeout
for"setTimeout 1"
(Timer queue:["setTimeout 1"]
). - Schedule
setImmediate
for"setImmediate 3"
(Check queue:["setImmediate 1", "setImmediate 3"]
). - Execute
setImmediate
for"setImmediate 1"
(Check queue:["setImmediate 3"]
). - Print
"setImmediate 1"
. - Schedule
setImmediate
for"setImmediate 2"
(Check queue:["setImmediate 3", "setImmediate 2"]
). - Execute
setImmediate
for"setImmediate 3"
(Check queue:["setImmediate 2"]
). - Print
"setImmediate 3"
. - Execute
setImmediate
for"setImmediate 2"
(Queue:[]
). - Print
"setImmediate 2"
. - Execute
setTimeout
from the Timers queue. - Print
"setTimeout 1"
.
But in reality, after step 8, it goes to the Timers queue. So my question is, why does it skip this nested setImmediate
callback in the queue and go to Timers?