Microtasks Run Before Tasks
What you'll learn: You'll discover why microtasks always drain completely before the next task can run from the task queue.
The Priority Rule
You already know JavaScript has two queues: the task queue (for callbacks like setTimeout) and the microtask queue (for promises). But there's a crucial priority rule: the event loop always empties the entire microtask queue before picking up the next task.
Think of it like airport security. Tasks are passengers waiting in the main line. Microtasks are last-minute boarding announcements. Before moving to the next passenger in line, security must handle all boarding announcements first—even if more announcements arrive while they're handling the current ones.
How It Works
After the call stack clears:
- The event loop checks the microtask queue
- It runs every microtask until the queue is empty
- Only then does it take one task from the task queue
- After that task completes, it checks microtasks again before the next task
This means if microtasks keep adding more microtasks, tasks will wait. The microtask queue must drain completely.
Why This Matters
This priority ensures promises resolve as quickly as possible. When you chain .then() handlers, they all run before any timers fire, even setTimeout(fn, 0). The microtask queue gets priority treatment.
Key Takeaway: The event loop drains the entire microtask queue before processing the next task, giving promises priority over timers and other task-queue callbacks.