Full answer
The event loop runs one task at a time. After each task, and after the main script, it runs every pending microtask. Only then can it take the next task from a queue like timers. Between tasks, the browser may also paint.
The rules to apply:
- Run the current script from top to bottom. This is synchronous code, and it includes the part of an async function before its first
await. - Run microtasks in the order they were queued. A microtask can queue more microtasks, and they run in the same round.
- Run the next task. A timer with
0delay is a task, and it never runs before microtasks that are already waiting.
In the snippet, after await is a microtask. The await splits the async function: the first part runs at once, and the rest is queued as a microtask. The order of queueing decides the order of printing among microtasks.
Reading the output in order:
start,async startandendprint during the synchronous run.- The promise callback, the
queueMicrotaskcallback andafter awaitprint next, in the order they were queued. timeoutprints last, even though its delay is 0.
A typical follow-up asks what happens if a microtask keeps queueing itself. The loop never reaches the timer or painting, and the page freezes.
This holds in browsers and in Node for these constructs. Node also has process.nextTick, which has its own queue and runs before promise microtasks, so avoid mixing it into a browser-focused answer.
console.log('start');
setTimeout(() => console.log('timeout'), 0);
Promise.resolve().then(() => console.log('promise'));
queueMicrotask(() => console.log('microtask'));
(async () => {
console.log('async start');
await null;
console.log('after await');
})();
console.log('end');Run with Node 24.22.1. The output matched the text in the answer in two runs. Run with Node and the output was identical in two runs. The same order is expected in browsers for these constructs, but this snippet was run in Node only.
Key points
- Synchronous code runs first, including the start of an async function.
- All microtasks run before the next task.
- await queues the rest of the function as a microtask.
- A zero delay timer is still a task and runs after the microtasks.
- Endless microtasks freeze rendering.
Common mistakes
- Thinking setTimeout 0 runs immediately.
- Believing the code after await runs synchronously.
- Mixing up microtask order with the order the callbacks are written. The order of queueing counts.
- Assuming process.nextTick belongs to the browser.
Follow-ups
- What changes if the promise callback itself queues a timer?
- Where does requestAnimationFrame fit in this order?
- What happens if a microtask queues another microtask forever?
Tips
- Explain with the three rules before reading the output.
- Say what is a task and what is a microtask in one line each.