Here are four lines. Most people who are new to asynchronous code get the output wrong on the first try.
console.log("start");
setTimeout(() => console.log("timer"), 0);
Promise.resolve().then(() => console.log("promise"));
console.log("end");
start
end
promise
timer
The timer was asked for first, with a delay of 0, and it prints last. To explain that, you need a picture of how the host runs your code. The host is the browser or Node. The part of it that decides what runs next is called the event loop.
Three places where code waits
The call stack holds the code that is running right now. When a function is called it goes on the stack. When it returns it comes off. JavaScript runs one thing at a time, so there is one stack.
The task queue holds callbacks that the host will run later. A timer callback goes here when its time is up. So does the callback for a click or for a network answer.
The microtask queue holds promise callbacks. When a promise is fulfilled or rejected, its then and catch callbacks go here. The code after an await goes here too.
The loop
The event loop repeats the same steps.
- Take one task and run it until the call stack is empty.
- Run every callback in the microtask queue, until that queue is empty.
- Go back to step 1 and take the next task.
Now follow the four lines.
- The whole script is the first task. It prints "start".
setTimeouthands a callback to the host. With a delay of 0, the callback goes to the task queue.thenputs its callback in the microtask queue, because the promise is already fulfilled.- The script prints "end" and finishes. The call stack is empty.
- Step 2: the microtask queue has one callback. It prints "promise".
- Step 3: the next task is the timer callback. It prints "timer".
Which parts are guaranteed
Two different rule books are at work, so it matters which one each claim comes from.
- "start" and "end" print before either callback. The JavaScript language guarantees that. Running code is never interrupted.
- "promise" prints after "end". The language guarantees that too. A promise callback never runs inside the code that added it.
- "promise" prints before "timer". The host decides that, because timers are not part of the JavaScript language. For browsers it is guaranteed: the HTML standard says the microtask queue is emptied after each task. Node runs a promise callback before the next timer as well. We ran this example in Node and in Chrome, and both print this order.
The first two hold everywhere JavaScript runs. The third holds in every browser and in Node. This lecture stays with one promise callback and one timer. The order among several timers, or several chains of promises, needs more rules than this model gives. Do not predict it from this lecture.
await uses the same queues
async function saveNote() {
console.log("saving");
await Promise.resolve();
console.log("saved");
}
setTimeout(() => console.log("timer"), 0);
saveNote();
console.log("end of script");
saving
end of script
saved
timer
saveNote runs until its await. The rest of the function becomes a microtask. The script continues and prints "end of script". Then the microtask runs and prints "saved". The timer is a task, so it comes after.
One thing at a time
Because there is one call stack, long synchronous code blocks everything else.
setTimeout(() => console.log("timer, asked for 0 ms"), 0);
let count = 0;
for (let i = 0; i < 20000000; i++) {
count = count + 1;
}
console.log("loop finished: " + count);
loop finished: 20000000
timer, asked for 0 ms
The timer was ready long before the loop ended. It could not run, because a task runs until the call stack is empty. The language guarantees that the loop finishes first.
This matters in a browser test. While a page runs a long piece of JavaScript, it cannot answer a click or update the screen. A test that clicks during that time waits, and with a short timeout it fails. The failure looks like a missing element. The real cause is a busy page.
Remember this
The event loop runs one task, then every microtask, then the next task. Promise callbacks and the code after await are microtasks. Timer callbacks are tasks. So after the current code finishes, a promise callback runs before a timer callback.
Reference: JavaScript execution model on MDN.