CodePark/ questions / Event loop phases
START PRACTICINGPRACTICE
Backend question · Node.js › Event loop phases

What does this log?

const fs = require("node:fs");

fs.readFile(__filename, () => {
  setTimeout(() => console.log("timeout"), 0);
  setImmediate(() => console.log("immediate"));
  process.nextTick(() => console.log("tick"));
});
tick immediate timeout

"tick immediate timeout" is correct. The readFile callback runs in the poll phase. tick runs right after that callback. The next phase is check, so setImmediate always runs before the loop goes back to the timers phase.

"tick, then timeout and immediate in a non-deterministic order" is wrong here. The order of
setTimeout(0) and setImmediate is only unpredictable when you schedule both from the main module. There, the order depends on how fast the loop starts.