The event loop
setTimeout(…, 0) looks like "right now", yet its callback runs after a callback passed to Promise.resolve().then(…). The reason is that the browser runs JavaScript one thing at a time and keeps work for later in different queues, by kind. This page runs short programs line by line and shows how the call stack, the task queue, the microtask queue and the console change.
It follows the browser event loop as the HTML Standard defines it. The console order each chapter shows is what the program printed when run in a real browser (Chromium).
The button in each chapter makes that event happen in the model, step by step.The button in each chapter makes that event happen in the model, step by step.
1One thing at a time
Calling a function puts a slot with its execution details (how far it got, its local variables) on top of the call stack. That slot is called a frame. When the function returns, its frame comes off and execution goes back to the function in the frame below. The last frame on is the first one off.
The script itself runs as one piece of work (a task), so while it runs a script frame sits at the bottom of the stack. In the program below, a() calls b(), and b() calls c(). So a, b, c pile up on top of script, and the console prints the innermost, c, first. Only when the script ends is the stack empty. There is only one such stack, so JavaScript does one thing at a time.
In the model on the right, the code is on the left and the state on the right. The black arrow marks the line running now, and lines that already ran keep a small dot. The "Step" button next to the run button moves one line at a time, so you can predict what changes next before you see it.
function c() { console.log('c'); }
function b() { c(); console.log('b'); }
function a() { b(); console.log('a'); }
a();
console.log('end');
// console: c, b, a, end
- The script starts, and calling a() puts a's frame on top of script.
- Inside a, b() goes on top of it.
- Inside b, c() goes on top.
- c logs 'c' and leaves.
- b logs 'b' and leaves.
- a logs 'a' and leaves.
- The last line logs 'end'.
- The script ends and the stack is empty.
The call stack runs only the function on top, and goes back down when that function returns.
2Later, please
setTimeout(callback, 0) does not call the callback now. Per the HTML Standard, once the given time has passed, the browser puts a task that runs the callback in a task queue. A task is the unit of work the event loop takes and runs one at a time, and the running script is itself a task.
The event loop takes the next task only after the current one has finished. So even with 0 ms, the callback runs after every remaining line of the script has run and the stack is empty. The delay means "at least this long", not "exactly this long"; the standard lets browsers wait longer.
console.log('1');
setTimeout(() => {
console.log('timeout');
}, 0);
console.log('2');
// console: 1, 2, timeout
- '1' is logged.
- The callback goes to the task queue.
- '2' is logged.
- The script ends and the stack is empty.
- The event loop runs the callback as the next task.
A setTimeout callback becomes a task and runs after everything running now has finished.
3Sooner than later
A callback passed to a promise's then goes to the microtask queue, not the task queue. The ECMAScript specification leaves scheduling promise callbacks to the host, and the HTML Standard puts them in the microtask queue. Adding then to a promise that is already settled puts the callback in that queue at once.
Every time a task finishes, the event loop performs a microtask checkpoint, and so does the end of a script once the call stack is empty. It runs everything in the microtask queue before moving on to the next task. That is why the promise callback runs before the timer that was set first.
setTimeout(() => {
console.log('timeout');
}, 0);
Promise.resolve()
.then(() => console.log('promise'));
console.log('sync');
// console: sync, promise, timeout
- The timer callback joins the task queue.
- The then callback joins the microtask queue.
- 'sync' is logged.
- With the stack empty, a microtask checkpoint begins.
- The then callback runs first.
- The timer callback runs as the next task.
A promise callback is a microtask: it runs as soon as the current work ends, before the next task.
4Predict the order
Now a program that mixes all three. Before pressing the run button, write down the order in which the numbers will appear in the console. Then move through it with the "Step" button, predicting at each step which queue changes, and check.
Three rules decide it. The script's lines run top to bottom, right away. Promise callbacks run as soon as the script ends. Timer callbacks run after that, as the next task.
console.log('1');
setTimeout(() => console.log('2'), 0);
Promise.resolve()
.then(() => console.log('3'));
console.log('4');
// console: 1, 4, 3, 2
- '1' is logged.
- The callback that logs '2' goes to the task queue.
- The callback that logs '3' goes to the microtask queue.
- '4' is logged and the script ends.
- The microtask logs '3'.
- The task logs '2'.
Synchronous code, then microtasks, then tasks: the console reads 1, 4, 3, 2.
5A microtask that queues a microtask
With a chain of then calls, the next then callback joins the microtask queue only after the previous callback has finished and its promise has settled. At first only the first callback is in the queue; the second waits.
The HTML Standard's microtask checkpoint takes and runs microtasks "while the event loop's microtask queue is not empty". So a microtask queued while the checkpoint runs also runs in the same checkpoint. However long the chain, all of it runs before the timer callback's turn. A microtask that keeps queuing new microtasks keeps pushing the next task back.
setTimeout(() => {
console.log('timeout');
}, 0);
Promise.resolve()
.then(() => console.log('then 1'))
.then(() => console.log('then 2'));
console.log('sync');
// console: sync, then 1, then 2, timeout
| Callback | Waits in | Runs |
|---|---|---|
| Function call | Call stack | When called |
| then callback | Microtask queue | As soon as the current task ends and the stack is empty, until the queue is empty |
| setTimeout callback | Task queue | After the delay, once earlier tasks and all microtasks have finished |
- The timer callback joins the task queue.
- Only the first then callback joins the microtask queue.
- 'sync' is logged and the script ends.
- then 1 runs, and then 2 joins the queue.
- then 2 runs, and the queue is empty.
- Only then does the timer callback run.
The microtask queue runs until it is empty, so a chain of then callbacks finishes before the next task.
Glossary
- Call stack
- Where the frames of running functions pile up. Only the function on top runs; it comes off when it returns.
- Frame
- A slot with one function's execution details: how far it got and its local variables.
- Event loop
- The browser's loop that takes tasks one at a time and performs a microtask checkpoint after each.
- Task
- The unit of work the event loop runs one at a time: running a script, a timer callback, handling an event.
- Task queue
- Where tasks wait to run. On this page the timer callbacks wait here.
- Microtask
- A small piece of work that runs as soon as the current task ends. A promise's then callback is a microtask.
- Microtask checkpoint
- The step that runs microtasks one by one until the queue is empty. It happens when a task ends and when a script ends with the stack empty.
- Promise
- An object for a value that will be settled later. then attaches a callback to run once it is.
- setTimeout
- A function that runs a callback as a task after a delay. The delay is a minimum, and timers nested more than five deep cannot go below 4 ms.