← JavaScript

Advanced · 2 of 11 · 9 min read

The event loop

How one thread runs everything, why promise callbacks always beat timers, and how to read any "what order does this log?" question off the rules.

  • Event loop
  • Call stack

JavaScript runs your code on one thread. Everything that looks concurrent — timers, network responses, clicks, promises — is the same single thread picking up work from queues when it has nothing else to do. The event loop is the part that decides what it picks up and when.

The pieces

The call stack is where functions run. Calling a function pushes a frame holding its arguments, its locals and where to return; returning pops it. It is why a stack trace reads as the chain of calls that got you here, and why a runaway recursion ends in RangeError: Maximum call stack size exceeded rather than running forever:

function loop() {
  return loop();
}
loop(); // RangeError — one frame per call, nothing ever pops

Web APIs are the parts that are not JavaScript at all — setTimeout, fetch, DOM events. When you call setTimeout, the timer is kept by the host, not by the engine. Your function goes nowhere near a queue until the delay has elapsed.

The task queue (also called the macrotask queue) is where those callbacks wait once they are ready: timers, I/O, UI events.

The microtask queue is a separate, higher-priority queue. Promise callbacks (.then, .catch, .finally), the continuation after an await, and queueMicrotask all land here.

The event loop does this, forever: if the stack is empty, drain every microtask; then take one task from the task queue and run it; repeat.

Reading an ordering question

That is the whole mechanism, so any snippet can be read off it. Take the canonical one:

console.log('Start');

setTimeout(() => console.log('Timeout'), 0);

Promise.resolve().then(() => console.log('Promise'));

console.log('End');
The JavaScript runtime stepped through one snippet: the engine with its heap and call stack, the host Web APIs, the microtask and task queues, the event loop moving callbacks onto the stack once it is empty, and the browser repainting between tasks.
JSHeapCall stack(script)Web APIsDOM eventsTimers — setTimeoutNetwork — fetchMicrotask queue — drained to emptyTask queue — one per turnConsoleStartEndPromiseTimeoutEvent looprepaintregisterwhen it firespromise jobscbjob

1 The script's own frame is on the stack — that is what (script) is — and console.log('Start') runs inside it. Plain code needs no queue and no loop: it just runs, immediately, and Start is printed. Both queues are still empty.

3 setTimeout does not pause anything and does not run anything. It hands the callback and the delay to the host and returns on the spot — watch cb leave the engine entirely. Timers are not part of the JavaScript language; they belong to the browser or to Node, which is why the box is a different colour.

5 The promise is already resolved, so its callback is ready at once. It still does not run: it is placed in the microtask queue. Note the arrow it came down — promise jobs are queued by the engine itself and never visit the Web APIs, which is the structural reason they are faster than any timer.

7 console.log('End') runs and prints End. This is still the first task, still the same uninterrupted run of the script, and two callbacks are now waiting in two different places. Nothing the loop does can begin while this frame is on the stack.

— The 0 ms timer expires almost immediately, so the host moves cb into the task queue. It is now ready — and still does not run. “0 ms” only ever meant “queue it as soon as you can”, never “run it now”.

— The script returns and the stack goes empty. This is the moment everything has been waiting for: the event loop is only allowed to act between tasks, and the stack emptying is what marks the end of one. Everything queued so far has been queued during a single task.

— Microtasks go first, and the queue is drained to empty — not one per turn. job runs on the now-free stack and prints Promise. If it queued another microtask, that one would run in this same pass too, before any task.

— Both the task and its microtasks are finished, so the browser gets its chance to repaint. This is the only kind of moment it gets: a task that runs for 200 ms is 200 ms in which the page cannot redraw, which is exactly why a long synchronous loop freezes a tab.

— Only now does the loop take one task. cb runs and prints Timeout. Final order: Start, End, Promise, Timeout — the zero-delay timer finished last, behind a promise that was queued after it.

The three rules the picture encodes, in the order they matter. One call stack, so nothing in either queue can begin while anything is on it — steps 1 to 5 all happen inside a single uninterrupted task. Two queues, and the microtask one is emptied completely before a single task is taken — that, and nothing about the delay, is why a resolved promise beats setTimeout(fn, 0). And the repaint only ever happens between tasks, which is the whole answer to “why does a long loop freeze the page?”.

Start, End, Promise, Timeout — and a microtask beating a zero-delay timer is the single fact that question is testing.

Scheduled with Queue Runs
nothing — plain code the stack now
Promise.then / catch / finally microtask before the loop moves on
await continuation microtask before the loop moves on
queueMicrotask microtask before the loop moves on
setTimeout / setInterval task a later turn
I/O and UI events task a later turn

Work scheduled from inside a callback

The follow-up question usually nests the scheduling. The rule still holds, you just have to notice when each thing joins its queue:

setTimeout(() => console.log('1'), 0);

Promise.resolve().then(() => {
  console.log('2');
  setTimeout(() => console.log('3'), 0);
});

console.log('4');

4 is synchronous. The stack empties, so the microtask runs and logs 2 — and the timer it schedules joins the back of the task queue, behind the one that has been waiting since line 1. So: 4, 2, 1, 3.

A microtask that queues another microtask is different: that one still runs in the same drain, before any task gets a turn. Which is also how you starve the timers completely:

function starve() {
  queueMicrotask(starve); // the drain never finishes
}

setTimeout(fn, 0) does not mean “now”

The delay is a minimum, not a promise. The callback cannot run until the stack is empty, and browsers also clamp the delay — roughly 1 ms, rising to 4 ms once timers are nested several levels deep. A blocking loop demonstrates it:

setTimeout(() => console.log('second'), 0);
for (let i = 0; i < 1e8; i++) {} // blocks the thread
console.log('first');            // still first

This is the same reason a long synchronous loop freezes the page. Rendering and event handling are tasks on this one thread, and a task runs to completion — so the browser cannot repaint or deliver your click until your loop finishes. The two fixes are to break the work into chunks that yield between them, or to move it off the thread entirely with a Web Worker.

await is a microtask boundary

An async function runs synchronously up to its first await. Everything after it is a microtask continuation — even when the thing you awaited was never a promise:

async function run() {
  console.log('a'); // synchronous
  await null;       // not a promise, and it still yields
  console.log('c'); // microtask
}

run();
console.log('b');
// a, b, c

Knowing this is what lets you answer “why did adding an await change my ordering?” — because you added a boundary, not because you made something slower.

Common mistakes

Thinking setTimeout(fn, 0) runs before a promise callback

Mistake. Reading the snippet top to bottom and expecting Timeout before Promise because the timer was scheduled first. Why it fails. Priority is by queue, not by scheduling order. The microtask queue is drained completely before a single task is taken. What to do instead. Sort the lines into synchronous / microtask / task first, then read each group in order.

Thinking the delay is when it runs

Mistake. Treating setTimeout(fn, 100) as “in exactly 100 ms”. Why it fails. It means “not before 100 ms, and then only once the stack is empty and the microtasks are drained”. A busy thread pushes it arbitrarily late. What to do instead. Use timers for ordering and deferral, never for precise timing. If something must be accurate, measure elapsed time rather than counting ticks.

Confusing the stack with the queues

Mistake. Saying a callback is “on the stack waiting to run”. Why it fails. The stack only holds calls in progress; a waiting callback is in a queue, or still held by the host API. Nothing is pulled off a queue while the stack has anything on it. What to do instead. Keep them separate when you explain it out loud — “the stack is what is running, the queues are what is waiting”. Interviewers notice.

Check yourself

3 questions from the bank on what you just read. Answering here does not affect your quiz history.

When does the event loop pick up a task from the macrotask queue?

Work scheduled from inside a microtask has to queue up like everything else.

In what order are these logged?

Code sample
setTimeout(() => console.log("1"), 0);

Promise.resolve().then(() => {
  console.log("2");
  setTimeout(() => console.log("3"), 0);
});

console.log("4");

Which of these schedules a **macrotask** rather than a microtask?

Practise Event loop and Call stack →

Further reading

Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.

Reaching the end of a lecture marks it as read.