Microtasks Always Run Before Tasks
You'll learn: Why promise callbacks execute before setTimeout callbacks, even when both are scheduled at the same time.
The Core Rule
When the call stack is empty, the event loop always checks the microtask queue first and completely drains it before looking at the task queue. This means every single microtask will run before even one task gets a chance—no matter which was scheduled first.
Think of it like airport security: microtasks are priority passengers who skip the regular line. Even if a regular passenger (task) arrived first, all priority passengers (microtasks) go through before any regular passenger does.
Why This Matters
setTimeout(() => {
console.log('Task: setTimeout');
}, 0);
Promise.resolve().then(() => {
console.log('Microtask: promise');
});
console.log('Stack: synchronous');
Output:
Stack: synchronous
Microtask: promise
Task: setTimeout
Even though setTimeout was scheduled first with zero delay, the promise callback (a microtask) runs first. Here's why:
- Synchronous code runs immediately:
'Stack: synchronous' - Call stack empties
- Event loop drains microtask queue:
'Microtask: promise' - Only then does the event loop check the task queue:
'Task: setTimeout'
This guarantee ensures that promise chains and async/await code complete their "next steps" before any timer callbacks or I/O operations interrupt.
Key Takeaway: Microtasks always fully drain before tasks run, giving promises higher priority than setTimeout in the event loop.