Mixing setTimeout and Promises
What you'll learn: How to predict which callbacks run first when you combine setTimeout (task queue) with Promises (microtask queue).
The Two-Queue Challenge
You've learned that setTimeout callbacks go into the task queue, while Promise .then() callbacks go into the microtask queue. When you mix both in the same code, understanding execution order becomes crucial.
The Golden Rule
Remember: All microtasks run before the next task. After the call stack empties, the event loop processes every microtask in the queue, then picks one task.
Predicting Execution Order
Consider this scenario:
console.log('Start');
setTimeout(() => {
console.log('Task 1');
}, 0);
Promise.resolve().then(() => {
console.log('Microtask 1');
});
console.log('End');
Execution order:
'Start'— synchronous (call stack)'End'— synchronous (call stack)'Microtask 1'— microtask queue (runs first after stack clears)'Task 1'— task queue (runs after all microtasks)
Even though setTimeout has a 0ms delay, it always waits for microtasks to finish.
More Complex Example
setTimeout(() => console.log('Task A'), 0);
Promise.resolve()
.then(() => console.log('Micro 1'))
.then(() => console.log('Micro 2'));
setTimeout(() => console.log('Task B'), 0);
// Output: Micro 1 → Micro 2 → Task A → Task B
Both chained .then() callbacks run before any setTimeout callback executes.
Key Takeaway: When mixing setTimeout and Promises, always remember that the microtask queue (Promises) gets priority over the task queue (setTimeout), no matter the delay value or code order.