I'm trying to understand Nodejs's official explanation about Event Loop. They have explained an example for Timers phase, but I'm unable to match it with their explanation about setTimeout and setImmediate.
Could you please explain, in detail, all the steps/processes/checks that Event Loop does for following pieces of codes?
Code 1:
setTimeout(() => {
console.log('timeout');
}, 0);
setImmediate(() => {
console.log('immediate');
});
Code 2:
const fs = require('fs');
fs.readFile(__filename, () => {
setTimeout(() => {
console.log('timeout');
}, 0);
setImmediate(() => {
console.log('immediate');
});
});
PS1: In comments, Mark has asked me to explain, which part is confusing. Here you go:
Following is summary of their explanation for their first example: "When the event loop enters the poll phase, it has an empty queue (fs.readFile() has not completed), so it will wait for the number of ms remaining until the soonest timer's threshold is reached...then wraps back to timers phase and runs its callbacks"
So, what I understand is that, accordingly for code 1, it should be as following: Poll phase has empty queue, and time threshold is reached. So, firstly setTimeout should run. Then going to check phase and should setImmediate runs. But it doesn't behave like this. why?