Interview frequency: …
Short answer
process.nextTick runs immediately after the current operation and before any later phase of the event loop, while setImmediate runs in the check phase of the event loop.
Explanation
Despite the historically misleading naming, process.nextTick is not part of libuv's phases themselves, but works as a top-priority microtask queue that is drained directly before control returns to the event loop. In contrast, setImmediate is registered as a callback invoked exclusively in the check phase after the poll phase ends. Overusing nextTick may cause starvation of I/O.
Code example
setImmediate(() => console.log("Check: immediate"));
process.nextTick(() => console.log("Microtask: nextTick"));Common mistakes
- Using process.nextTick in recursive calls, which freezes all I/O.
Follow-up questions
- What are the basic phases of the event loop in Node.js and how does it handle different tasks?
- How does the priority of microtasks differ from macrotasks in task processing in Node.js?