This is related to the event loop , you can find a good documentation about this at this link https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/ .
In short setImmediate is executed after the poll phase , setTimeout is executed during the "timers" phase so there the execution order depends on the first phase executed into your node process.
If you put setTimeout and setImmediate into an I/O callback ( pending callbacks ) the setImmediate will be executed first . ( See code below that is also present into the previous link )
// timeout_vs_immediate.js
const fs = require('fs');
fs.readFile(__filename, () => {
setTimeout(() => {
console.log('timeout');
}, 0);
setImmediate(() => {
console.log('immediate');
});
});
