Node.js
/Advanced
Macrotasks Queue
Definition
Also simply known as the Task Queue. This represents the standard asynchronous callbacks handled by the Event Loop phases (like `setTimeout`, `setImmediate`, and I/O callbacks).
Explain Like I'm New
Macrotasks are the 'normal' asynchronous tasks. When you read a file, or wait for an API request, or set a timer, you are creating a Macrotask. The Event Loop processes these one by one during their respective phases.
Real World Example
Using `setTimeout(cb, 0)` is a classic way to push a heavy calculation to the Macrotask queue, allowing the server to handle a quick HTTP request first before locking up the CPU with the calculation.
Common Use Cases
- •Deferring heavy execution
- •Understanding performance flow
Terminal Output
bash / terminal
console.log("A: Main script running");
// Macrotask 1 (Scheduled for Timers phase)
setTimeout(() => console.log("E: Macrotask (Timeout)"), 0);
// Macrotask 2 (Scheduled for Check phase)
setImmediate(() => console.log("F: Macrotask (Immediate)"));
// Microtask 1
Promise.resolve().then(() => console.log("C: Microtask 1 (Promise)"));
// Microtask 2
queueMicrotask(() => console.log("D: Microtask 2 (Queue)"));
console.log("B: Main script ending");
/*
PREDICT THE ORDER!
1. A (Main thread)
2. B (Main thread)
--- Main script ends. Engine checks Microtasks! ---
3. C (VIP queue)
4. D (VIP queue)
--- Microtasks empty. Event loop begins! ---
5. E (Timers Phase)
6. F (Check Phase)
*/
Interview Questions
basic
- Are `setTimeout` callbacks Microtasks or Macrotasks?
intermediate
- Which executes first: A Microtask or a Macrotask?
advanced
- Why is `setTimeout(cb, 0)` not actually 0 milliseconds in Node?