Interview frequency: …
Short answer
Microtasks run as soon as the current task ends and before any later macrotask, which means the microtask queue is drained completely before advancing through the event loop phases.
Explanation
Macrotasks are the events of the event loop phases such as setTimeout timers, I/O listeners, and setImmediate events. Microtasks include process.nextTick, promise callbacks, and queueMicrotask. When the current JavaScript code finishes, the microtask queue is fully drained before advancing to the next phase.
Code example
queueMicrotask(() => console.log("Micro"));
setTimeout(() => console.log("Macro"), 0);Common mistakes
- Putting an infinite loop inside queueMicrotask or process.nextTick, which completely blocks the event loop from any I/O.
Follow-up questions
- What are the basic phases of the event loop in Node.js and how does it handle different tasks?
- What is the essential difference between process.nextTick() and setImmediate() in Node.js?