Sub topic 5
How the Event Loop Schedules Callbacks
This chapter assumes you can write callbacks, you know that setTimeout runs its callback later, and you have seen Promise.resolve().then(...). The question here is when "later" happens. Three structures decide it: the call stack, the task queue, and the microtask queue.
The Three Structures
The call stack holds the functions that are running right now. JavaScript runs one function at a time on a single thread. When a function returns, it is popped off the stack.
The task queue (also called the macrotask queue) holds callbacks that are waiting to run. Timer callbacks from setTimeout and setInterval go here, along with I/O callbacks and UI events.
The microtask queue holds higher-priority callbacks. Promise reactions (.then, .catch, .finally), code after an await, and functions passed to queueMicrotask go here.
The event loop moves callbacks from the queues onto the stack. It only does this when the stack is empty.
The Scheduling Rule
The event loop follows one rule:
- Run the current synchronous code until the call stack is empty.
- Run every microtask in the microtask queue, including microtasks added during this step.
- Take one task from the task queue and run it.
- Go back to step 2.
A delay of 0 does not mean "run now". It means the callback goes into the task queue as soon as possible, and it still has to wait for the stack to empty:
console.log('A');
setTimeout(() => console.log('C'), 0);
console.log('B');
// Output: A, B, CMicrotasks get ahead of timers because step 2 always comes before step 3:
setTimeout(() => console.log('timeout'), 0);
Promise.resolve().then(() => console.log('microtask'));
console.log('sync');
// Output: sync, microtask, timeoutTracing a Mixed Example
The next example registers microtasks from inside a task. The numbers in the log messages show the order they print in.
console.log('1 sync');
setTimeout(() => {
console.log('4 first timeout');
Promise.resolve().then(() => console.log('5 microtask from timeout'));
}, 0);
setTimeout(() => console.log('6 second timeout'), 0);
Promise.resolve().then(() => console.log('3 microtask'));
console.log('2 sync');Here is the trace:
| Step | Call stack runs | Task queue after | Microtask queue after |
|---|---|---|---|
| Script | logs 1 and 2 | timeout1, timeout2 | microtask 3 |
| Drain microtasks | logs 3 | timeout1, timeout2 | empty |
| One task | timeout1 logs 4 | timeout2 | microtask 5 |
| Drain microtasks | logs 5 | timeout2 | empty |
| One task | timeout2 logs 6 | empty | empty |
Message 5 prints before message 6. The microtask created inside the first timer runs before the loop takes the next task. Browsers and Node.js 11 and later behave this way.
Common Errors
- Treating
setTimeout(fn, 0)as immediate. The callback runs only after all synchronous code and all pending microtasks have finished. - Assuming the timer delay is exact. The delay is a minimum. If a long synchronous loop keeps the stack busy, every queued callback waits for it.
- Blocking the loop. Because there is one thread, a slow synchronous function freezes timers, I/O callbacks, and in browsers, rendering too.
Exercises
Exercise
What does this code print, and in what order? setTimeout(() => console.log('a'), 0); queueMicrotask(() => console.log('b')); Promise.resolve().then(() => { console.log('c'); queueMicrotask(() => console.log('d')); }); console.log('e');
Show answer
e, b, c, d, a. The synchronous log 'e' runs first. Then the microtask queue drains in order: 'b', then 'c'. Running 'c' queues 'd', and 'd' still runs during the same drain. Only after the microtask queue is empty does the timer task log 'a'.
Exercise
A page calls setTimeout(update, 100) and then runs a synchronous loop that takes 500 ms. Roughly when does update run, and why?
Show answer
After about 500 ms, not 100 ms. The timer callback enters the task queue after 100 ms, but the event loop cannot move it onto the call stack until the synchronous loop finishes and any pending microtasks have run.