Predict console.log order: microtasks before timers
Predict the output of a short script by following synchronous code, the microtask queue and a zero-delay timer.
You have a script with a setTimeout of 0, a promise callback and an await, and you need to say what order the logs print in. The timer says zero milliseconds, so the tempting guess puts it near the top. It prints last.
console.log('1 sync start')
setTimeout(() => console.log('7 timeout'), 0)
Promise.resolve().then(() => console.log('4 then'))
queueMicrotask(() => console.log('5 queueMicrotask'))
async function run() {
console.log('2 before await')
await null
console.log('6 after await')
}
run()
console.log('3 sync end') // prints 1 to 7 in orderThe number at the start of each message is the position it printed in, and node demo.mjs printed the lines as 1 to 7. I ran the script twice and got the same order both times.
Three stages, in this order
In this example, the call stack first runs all the synchronous code, including the part of run() before its await. So run() logs 2 before await ahead of 3 sync end.
Second, the microtask queue. A .then callback, a queueMicrotask callback and the code after an await wait there. Here the promise is already fulfilled and await null can schedule its continuation immediately, so the queue holds 4 then, 5 queueMicrotask and 6 after await in that order.
Third, the timer callback. The setTimeout call returns at once and the script moves on.
With a delay of 0 the callback still waits until the stack is empty and the microtask queue has drained. 7 timeout prints last.
diagram
Print order: stack, then microtasks, then one timer
The queue drains until it is empty
A microtask that queues another microtask does not let the timer in between. The new one joins the same queue and runs before the timer.
setTimeout(() => console.log('timeout'), 0)
Promise.resolve().then(() => {
console.log('then A')
queueMicrotask(() => console.log('queued from A'))
}) // prints then A, queued from A, timeoutThe output is then A, queued from A, timeout, even though the timer was registered first.
Predict the order
I use three steps on any snippet like this, and I write the print numbers in the margin as I go.
- Print the synchronous lines top to bottom, including an async function's body up to its first
await. - Add each
.thencallback, eachqueueMicrotaskcallback and each line after anawaiton a ready value. Keep the order in which the queuing lines ran. - Once the microtask queue drains, run the timer in this example. A promise that is still pending can settle after a timer.
Apply them to demo.mjs and you get 1 to 7 without running it.