As asked
Walk me through the Node.js event loop phases in the order they execute. What happens in each phase, and where do setImmediate, setTimeout, and process.nextTick fit in?
Sample answer outline
A strong answer names all six phases in order: timers, pending callbacks, idle/prepare, poll, check, close callbacks. The timers phase is the first phase of each loop iteration and runs callbacks for setTimeout and setInterval whose delay has elapsed. The poll phase comes later: it retrieves and processes I/O events, and will block waiting for I/O if no timers are pending. setImmediate runs in the check phase, which comes immediately after poll. Because check follows poll in the same iteration, setImmediate fires before a setTimeout(fn, 0) when both are scheduled inside an I/O callback. process.nextTick is not part of any phase: it drains its queue after the current operation finishes and before the event loop moves to any phase, making it higher priority than setImmediate or setTimeout in all cases.
Expect these follow-ups
- What happens if you call process.nextTick recursively without a base case?
- When would you choose setImmediate over setTimeout(fn, 0)?