1. Timer in timers phase
setTimeout(fn, 0) schedules its callback for the timers phase once the (effectively zero) threshold elapses.
setTimeout(() => console.log('timeout'), 0);Typorithm · hard
Step 1 of 8 · intro card
Event Loop
setImmediate runs in the check phase (right after poll) while setTimeout(fn, 0) runs in the timers phase. Inside an I/O callback the loop is already in poll, so check is next and setImmediate always fires before setTimeout(0). Outside any I/O the ordering between the two is nondeterministic.
setImmediate schedules its callback for the check phase, which runs immediately after the poll phase, while setTimeout(fn, 0) schedules for the timers phase at the start of the loop.
Inside an I/O callback you are already in the poll phase, so the very next phase is check — that is why setImmediate always fires before setTimeout(0) in that context.
Outside of any I/O cycle the relative order of setTimeout(fn, 0) and setImmediate is nondeterministic, because it depends on how much time the process spent reaching the loop, which can land either before or after the 1ms timer threshold.
setImmediate -> check phase; setTimeout(fn, 0) -> timers phase.
Inside I/O, setImmediate always beats setTimeout(0).
Outside I/O the ordering of the two is nondeterministic.
// outside any I/O, order is NOT guaranteed
setTimeout(() => console.log('timeout'), 0);
setImmediate(() => console.log('immediate'));
// inside an I/O callback, immediate ALWAYS wins
const fs = require('fs');
fs.readFile('file.txt', () => {
setTimeout(() => console.log('timeout'), 0); // timers phase
setImmediate(() => console.log('immediate')); // check phase, runs first
});Connect each part of the code to the concept before you type.
setTimeout(fn, 0) schedules its callback for the timers phase once the (effectively zero) threshold elapses.
setTimeout(() => console.log('timeout'), 0);setImmediate schedules its callback for the check phase, which runs right after the poll phase.
setImmediate(() => console.log('immediate'));This callback runs in the poll phase, so the next phase is check — making setImmediate fire before the timer.
fs.readFile('file.txt', () => {From inside a poll-phase I/O callback, check is the very next phase, so setImmediate always beats setTimeout(0).
setImmediate(() => console.log('immediate')); // check phase, runs firstRead the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.