Interview frequency: …
Short answer
The event loop goes through successive phases: timers, pending callbacks, idle/prepare, poll, check, and close callbacks, with microtasks processed between the phases.
Explanation
The event loop is managed by the libuv library; its cycle begins with the timers phase (running the callbacks of setTimeout and setInterval), followed by pending callbacks for deferred I/O errors, then poll to wait for new I/O events, then check to run setImmediate callbacks, and finally close callbacks to close sockets and handles. The microtask queue (such as process.nextTick and promises) is drained as soon as each operation or phase finishes, before moving on to the next phase.
Code example
setTimeout(() => console.log("Timer"), 0);
setImmediate(() => console.log("Immediate"));
process.nextTick(() => console.log("Next Tick"));Common mistakes
- Believing that setTimeout(fn, 0) runs immediately at the same moment without waiting for the event loop cycle.
- Ignoring the priority of process.nextTick over the other promise microtasks.
Follow-up questions
- What is the essential difference between process.nextTick() and setImmediate() in Node.js?
- How does the priority of microtasks differ from macrotasks in task processing in Node.js?