Why a Promise Beats setTimeout Zero
The single most asked event loop question has one answer, and once you can say it precisely you can predict any variation of it.
The microtask queue is drained completely between macrotasks, so every pending promise callback runs before the next timer. Predicting mixed output is a matter of sorting the work into synchronous, microtask and macrotask, in that order.
EXERCISE
1The Question, and the Precise Answer
Almost every interview version of this is the same question wearing different code.
The canonical form:
console.log("1");
setTimeout(() => console.log("2"), 0);
Promise.resolve().then(() => console.log("3"));
console.log("4");
// 1
// 4
// 3
// 2
The answer, said precisely:
Synchronous code runs first and prints 1 and 4. Both callbacks are then waiting, but in different queues. The event loop drains the microtask queue completely before taking anything from the callback queue, so the promise callback prints 3, and only then does the timer print 2.
Two details make that answer better than "promises are faster". Promises are not faster. The timer was ready first, at zero milliseconds. And it is not about registration order either, since the timer was registered before the promise.
It is about which queue, and the fixed rule that one of them is emptied before the other is touched.
A variation, to check the rule rather than the example:
setTimeout(() => console.log("timeout 1"), 0);
setTimeout(() => console.log("timeout 2"), 0);
Promise.resolve().then(() => console.log("promise 1"));
Promise.resolve().then(() => console.log("promise 2"));
// promise 1
// promise 2
// timeout 1
// timeout 2
Both promises before both timers, and within each queue, registration order holds. Two rules, applied in order, predict everything.
And the version that catches people who learned only the slogan:
setTimeout(() => {
console.log("timeout");
Promise.resolve().then(() => console.log("promise inside timeout"));
}, 0);
setTimeout(() => console.log("second timeout"), 0);
// timeout
// promise inside timeout
// second timeout
The promise created inside the first timer still runs before the second timer. The loop takes one macrotask, runs it, then drains microtasks again before taking the next. "Drain microtasks between every macrotask" is the rule; "promises first" is only a consequence of it.
Pro Tip: Learn the rule as a loop rather than as a fact: run one task, drain all microtasks, run one task, drain all microtasks. Every question of this shape is that loop applied to the code in front of you, and you can answer variations you have never seen without memorising them.
EXERCISE
2Predicting Mixed Output
A method that works every time: three buckets, filled in order, no guessing.
The method:
// 1. SYNCHRONOUS everything that runs before the stack empties
// 2. MICROTASKS every .then, .catch, .finally, await resumption
// 3. MACROTASKS setTimeout, setInterval, events, one at a time
//
// Write out bucket 1 fully, then bucket 2 fully, then bucket 3 one item
// at a time, re-draining bucket 2 after each.
Worked through a larger example:
console.log("A");
setTimeout(() => console.log("B"), 0);
Promise.resolve()
.then(() => console.log("C"))
.then(() => console.log("D"));
queueMicrotask(() => console.log("E"));
console.log("F");
Bucket 1 is A and F. Bucket 2 starts with C and E, in registration order, and D joins it once C has run. Bucket 3 is B.
// A
// F
// C
// E
// D
// B
D lands after E because it was not queued until C finished, and E was already waiting by then. This is the detail most people get wrong, and the bucket method gets it right without any extra rule.
Notice that nothing about this required tracing execution mentally. The buckets encode the rule, so filling them in is mechanical, and the only judgement needed is spotting that D is not queued until C has run.
Nested timers go to the back of their own queue:
setTimeout(() => {
console.log("outer");
setTimeout(() => console.log("inner"), 0);
}, 0);
setTimeout(() => console.log("sibling"), 0);
// outer
// sibling
// inner
inner was queued while outer was running, so sibling was already ahead of it. A timer created inside a timer never jumps the queue; it joins the back of it like any other.
And a mixed case worth tracing slowly:
console.log("start");
setTimeout(() => {
console.log("t1");
Promise.resolve().then(() => console.log("p1"));
}, 0);
setTimeout(() => {
console.log("t2");
Promise.resolve().then(() => console.log("p2"));
}, 0);
Promise.resolve().then(() => console.log("p0"));
console.log("end");
// start
// end
// p0
// t1
// p1
// t2
// p2
One task, then a full drain, then the next task. p1 runs between the two timers, not after both.
When you are asked to predict output, resist reading top to bottom. Sort first, then read. The buckets take fifteen seconds to write down and remove every opportunity to guess, which is exactly what the question is testing.
EXERCISE
3await Is a Microtask Too
Every await resumption goes through the microtask queue, which makes async functions predictable by the same rule.
Unit 6 covers async/await properly. One thing belongs here, because it is the same mechanism and the same question in different syntax.
An async function runs synchronously until its first await:
async function run() {
console.log("inside, before await");
await null;
console.log("inside, after await");
}
console.log("before call");
run();
console.log("after call");
// before call
// inside, before await
// after call
// inside, after await
The first two lines ran on the stack with no waiting at all. await null does not wait for anything meaningful; what it does is suspend the function and queue the rest of it as a microtask. So after call runs, the stack empties, and only then does the function resume.
That is worth saying plainly: await is not a pause in place. It is a return, with the remainder scheduled.
Which means await and .then interleave predictably:
async function a() {
console.log("a1");
await null;
console.log("a2");
}
console.log("start");
a();
Promise.resolve().then(() => console.log("then"));
console.log("end");
// start
// a1
// end
// a2 <- queued first, so it resumes first
// then
a2 was queued when a hit its await, which happened before the .then was registered. Registration order within the microtask queue decides the rest.
And the same beats-a-timer result, in async form:
async function run() {
await null;
console.log("after await");
}
setTimeout(() => console.log("timeout"), 0);
run();
// after await
// timeout
No new rule. The resumption is a microtask, and microtasks drain before the callback queue.
One practical consequence worth carrying forward:
async function load() {
console.log("1");
const data = await fetchSomething(); // suspends here
console.log("3"); // resumes as a microtask
return data;
}
console.log("0");
load();
console.log("2");
// 0
// 1
// 2
// 3
The numbers only make sense if you read await as "return now, continue later". Reading it as "wait here" predicts 0 1 3 2, which is wrong.
Pro Tip: Whenever async output confuses you, mentally rewrite the
awaitas a.thenon the rest of the function. The two are the same scheduling with different syntax, and the.thenversion makes the boundary visible, which is exactly the boundary the ordering depends on.
