JavaScript
/Advanced
Microtasks vs Macrotasks
Definition
JavaScript divides asynchronous tasks into two distinct queues. The Macrotask Queue (setTimeout, setInterval, I/O) and the Microtask Queue (Promises, MutationObserver). The Microtask queue always has strictly higher priority.
Explain Like I'm New
Imagine the JS engine is a doctor. Macrotasks are scheduled patient appointments. Microtasks are emergency room patients. When the doctor finishes their current appointment, they check the ER (Microtask queue). They will process EVERY ER patient until the room is empty before they accept the next scheduled appointment (Macrotask).
Real World Example
If you call a `setTimeout(cb, 0)` and a `Promise.resolve().then(cb)` at the exact same time, the Promise callback will ALWAYS execute first because it enters the VIP Microtask queue.
Common Use Cases
- •Predicting exact code execution order
- •Preventing UI blocking
Interactive Example
Loading...
Console output will appear here...
Interview Questions
basic
- Which queue has higher priority: Microtasks or Macrotasks?
intermediate
- Give examples of Microtasks and Macrotasks.
advanced
- What happens if a Microtask schedules another Microtask recursively?