Sub topic 5
One Turn of the Event Loop
This chapter assumes you know how JavaScript functions and callbacks work, can read basic Promise code, and can run a script in a browser console or with Node.js. It also builds on the previous chapters: the call stack, host APIs, and the task queue. Here those pieces come together into one repeating cycle, the event loop.
The Loop in One Sentence
The event loop is a simple algorithm the host (browser or Node.js) runs forever: take one task, run it until the call stack is empty, run all pending microtasks, maybe update the screen, then repeat.
Each pass through that cycle is called a turn (some sources say "tick" or "iteration"). Asynchronous JavaScript makes sense once you can picture a single turn clearly.
The Steps, One at a Time
Step 1: Pick one task
The loop looks at the task queue and takes the oldest task, meaning the first one in. A task is a unit of work such as a timer callback, a click handler, a message from a worker, or the initial run of a script. Running your script's top-level code is itself the first task.
The loop takes exactly one task per turn. It does not empty the whole task queue at once. This detail matters later, because the microtask queue behaves differently.
Step 2: Run it to completion
The task's callback is pushed onto the call stack and runs. It may call other functions, which push and pop frames as usual. The task is finished only when the call stack is empty again.
Nothing interrupts this step. If a timer expires or the user clicks while the task runs, the host just adds a new task to a queue. That new task waits its turn.
Step 3: The microtask checkpoint
Once the stack is empty, the loop performs a microtask checkpoint. It runs every microtask in the microtask queue, including any new microtasks added while that is happening, until the queue is empty. Promise reactions are the most common microtasks.
A later chapter covers the microtask queue in detail. For now, remember where it sits: after each task and before the next one.
Step 4: Maybe render
In a browser, the loop may now update the page: run style and layout calculations and paint the result. It does not do this every turn. Browsers usually render in step with the display's refresh rate, for example about every 16.7 ms on a 60 Hz screen, and skip rendering when nothing has changed or the page is hidden. Node.js has no rendering step. Rendering gets its own chapter later.
Step 5: Repeat, or sleep
The loop goes back to step 1. If no task is waiting, it does not spin and burn CPU. It sleeps until the host adds a new task, for example when a timer expires or a network response arrives. In Node.js, if no tasks are queued and no pending work (open sockets, active timers) could ever produce one, the process exits.
A Runnable Model of the Loop
The real event loop lives inside the host and is written in C++. The plain JavaScript model below runs the same algorithm on fake queues, so you can watch each turn happen.
const taskQueue = [];
const microtaskQueue = [];
function enqueueTask(name, fn) {
taskQueue.push({ name, fn });
}
function enqueueMicrotask(fn) {
microtaskQueue.push(fn);
}
function runMicrotaskCheckpoint() {
// Drain completely, including microtasks added during draining
while (microtaskQueue.length > 0) {
const job = microtaskQueue.shift();
job();
}
}
function runEventLoop() {
let turn = 0;
while (taskQueue.length > 0) {
turn++;
const task = taskQueue.shift(); // exactly one task per turn
console.log(`--- turn ${turn}: ${task.name}`);
task.fn(); // run to completion
runMicrotaskCheckpoint(); // then all microtasks
// a browser might render here
}
console.log('--- no tasks left: a real loop would sleep here');
}
// The script itself is the first task
enqueueTask('main script', () => {
console.log('script runs');
enqueueTask('timer A', () => {
console.log('timer A runs');
enqueueTask('timer C (queued by A)', () => console.log('timer C runs'));
});
enqueueTask('timer B', () => console.log('timer B runs'));
enqueueMicrotask(() => console.log('microtask from script'));
});
runEventLoop();Running this with node prints:
--- turn 1: main script
script runs
microtask from script
--- turn 2: timer A
timer A runs
--- turn 3: timer B
timer B runs
--- turn 4: timer C (queued by A)
timer C runs
--- no tasks left: a real loop would sleep hereNotice three things. The microtask ran at the end of turn 1, before any timer. Timer C was queued during turn 2 but went to the back of the queue, behind timer B. And each turn handled exactly one task.
The Same Behaviour with Real Timers
Here is the same pattern using real setTimeout calls. It produces the same order in browsers and in Node.js:
setTimeout(() => {
console.log('task 1 start');
setTimeout(() => console.log('task 3 (queued by task 1)'), 0);
console.log('task 1 end');
}, 0);
setTimeout(() => console.log('task 2'), 0);
// Output:
// task 1 start
// task 1 end
// task 2
// task 3 (queued by task 1)Task 1 runs from start to finish without being interrupted, even though it scheduled more work. Task 3 was queued after task 2 already existed, so it runs last.
Edge Cases Worth Knowing
There is more than one task queue
The specification lets a browser keep several task queues, for example one for user input, one for timers, and one for networking. On each turn, the browser chooses which queue to take from. Tasks inside one queue keep their order, but no order is guaranteed between queues. Many browsers favour input tasks so the page feels responsive. Don't write code that depends on a click handler running before or after a timer callback that became ready at about the same moment.
Node.js organises turns into phases
Node.js uses the same core idea of tasks, run to completion, and microtasks between callbacks. It splits each turn into phases (timers, I/O polling, setImmediate callbacks, and others), each with its own queue. A later chapter covers those phases.
The first task is your script
Top-level code is not "before" the event loop. It is the first task. This is why a promise callback created at top level runs before any timer: the microtask checkpoint follows that first task.
Common Misconceptions
| Misconception | What actually happens |
|---|---|
| A timer callback interrupts running code when its delay expires | Expiry only queues a task. It runs after the current task and its microtasks finish. |
| The loop empties the whole task queue each turn | It takes one task per turn. Only the microtask queue is drained completely. |
| The browser repaints after every task | Rendering happens when the browser decides it is time, usually once per display frame. |
| An idle loop spins and uses CPU | The loop sleeps until the host queues a new task. |
| Tasks from different sources run strictly in the order they became ready | Order is guaranteed within one queue only. The host picks between queues. |
Exercises
Exercise
In the runnable model above, suppose timer B's callback calls enqueueMicrotask(() => console.log('micro from B')). Where does "micro from B" appear in the output, and why?
Show answer
It appears right after "timer B runs" and before "--- turn 4: timer C (queued by A)". After timer B's task finishes, the loop runs a microtask checkpoint, which drains all microtasks before the next turn picks up timer C.
Exercise
A click handler takes 500 ms to run. During that time a 0 ms timer expires and the user clicks a second time. Describe what the event loop does from the moment the first handler finishes.
Show answer
When the first handler returns and the stack is empty, the loop runs any pending microtasks, may render, and then starts a new turn. The timer task and the second click task are both waiting. They may sit in different queues, so the browser chooses which to run first (often the input). Each runs in its own turn, followed by its own microtask checkpoint. Neither could run during the 500 ms.
Exercise
Predict the output of this code and explain it in terms of turns: setTimeout(() => console.log('X'), 0); Promise.resolve().then(() => console.log('Y')); console.log('Z');
Show answer
Z, Y, X. Turn 1 is the script task: it logs Z, queues a timer task, and queues a microtask. The microtask checkpoint at the end of turn 1 logs Y. Turn 2 runs the timer task and logs X.