Two queues, not one
Lesson 4-1 showed the task queue (also called the macrotask queue), where setTimeout callbacks wait. There is a second, higher-priority line: the microtask queue. Promise callbacks (.then, .catch, await continuations) go there.
The full event-loop rule:
- Run the script to completion.
- Drain the entire microtask queue (including microtasks queued by other microtasks).
- Run one macrotask (like a timeout), then drain microtasks again. Repeat.
So a resolved promise's .then always beats a setTimeout(..., 0), no matter the order you wrote them in.
The split exists because promise reactions were designed to run as soon as possible after the current work, without letting coarser work — timers, clicks, network callbacks — cut in front of them. It matters in production: code that assumes a 0 ms timeout runs before a .then is simply wrong, and ordering bugs like that are miserable to find.
Code exercise · javascript
Run it and study the order. The timeout was written BEFORE the promise, but the promise callback is a microtask and jumps ahead of it.
Quiz
Which statement is true about the microtask queue?
await rides the same queue
await (Unit 6 makes it your daily tool) is built directly on this machinery: everything after an await line is scheduled as a microtask. The function pauses, the rest of the script runs, and the continuation comes back through the microtask queue — which is why the output below interleaves the way it does.
Code exercise · javascript
Run it. `main` runs synchronously up to the `await` and prints A. The rest of `main` is parked as a microtask, the script prints B, then the microtask resumes with C.
The interview script
When asked "why does setTimeout(fn, 0) not run immediately?", answer in three beats:
- JavaScript is single-threaded, running code on a call stack.
- Timers queue a macrotask, which only runs when the stack is empty.
- Promise callbacks are microtasks, drained before the next macrotask, so
.thenbeatssetTimeout.
Say those three sentences and you have answered 90% of event-loop questions. The remaining 10% is applying them to a printed-order puzzle, like the one below.
Problem
The classic ordering puzzle. Write the five letters in print order, separated by spaces: ```javascript console.log("a"); Promise.resolve() .then(() => console.log("b")) .then(() => console.log("c")); setTimeout(() => console.log("d"), 0); console.log("e"); ```