Microtask vs Macrotask Queue
1. Definition
Microtask and Macrotask queues are part of the Event Loop in JavaScript. They store asynchronous callbacks, but differ in priority and execution order.
2. Microtask Queue
- High priority queue
- Executed immediately after current code
- Runs before Macrotasks
- Examples: Promise.then(), process.nextTick()
3. Macrotask Queue
- Lower priority queue
- Executed after Microtasks
- Handled in Event Loop phases
- Examples: setTimeout(), setImmediate()
4. Key Differences
- Priority: Microtask → Higher | Macrotask → Lower
- Execution: Microtask runs first
- Queue Type: Microtask queue vs Event Loop phases
- Examples: Promise vs setTimeout
5. Execution Flow
1. Execute Sync Code 2. Execute Microtasks (ALL) 3. Execute ONE Macrotask 4. Repeat
6. Example
console.log("Start");
setTimeout(() => console.log("Timeout"), 0);
Promise.resolve().then(() => console.log("Promise"));
console.log("End");👉 Output:
Start End Promise Timeout
👉 Promise (Microtask) runs before setTimeout (Macrotask).
7. Why This is Important
- Helps understand execution order
- Important for debugging async code
- Frequently asked in interviews
8. Important Note
If too many Microtasks are added (like process.nextTick or Promise), they can block the Event Loop and delay Macrotasks.
Interview Points
- Microtask queue has higher priority
- Promises and nextTick are Microtasks
- setTimeout is a Macrotask
- Microtasks run before Macrotasks