Which runs first, Promise callbacks or setTimeout?
Question
What does this browser snippet log, in order? Explain where the nested microtask joins the queue.
console.log('open');
setTimeout(() => console.log('timer'), 0);
Promise.resolve().then(() => {
console.log('promise');
queueMicrotask(() => console.log('nested'));
});
queueMicrotask(() => console.log('queued'));
console.log('close');Show hints (2)
- "START ON STACK"
Read the lines that run before the snippet returns.
- "FOLLOW THE QUEUE"
Both the promise handler and
queueMicrotaskadd microtasks. Look at when each one is added.
Show checked explanation
The order is open, close, promise, queued, nested, timer. The browser drains the microtask queue after the snippet. The nested callback joins behind queued, which is already waiting.
The log order and swapped enqueue order were checked in Chromium.
Walkthrough
The snippet prints open and close while it schedules the callbacks. The first microtask prints promise and adds nested to the end of the queue. The browser then runs queued and nested. The timer callback runs in a later task.
Common mistakes
- Reading a zero-millisecond timeout as a synchronous function call.
- Moving
nestedahead ofqueuedbecause it was scheduled from inside the first callback. - Putting the promise reaction in the timer task queue.
Follow-up questions
- "What if the
queueMicrotaskthat logsqueuedcomes before.then?"queuedmoves beforepromise.nestedstill comes afterpromise, andtimerstill comes last. - "Can many microtasks delay a timer or a paint?" Yes. Microtasks can keep adding more microtasks during the same checkpoint. That delays the next task and can delay rendering.
What a strong answer covers
Trace the synchronous calls first, then the microtasks in queue order, then the timer. Explain the nested enqueue explicitly.
Open in interactive practice deck →