Event loop

JavaScript does one thing at a time, but it can wait on many. Watch the call stack, microtasks, tasks and screen drawing take turns one step at a time, then put blocks together and guess for yourself what prints first.

Level: IntermediateWatch: 22 steps · ~1.5 minBuild blocks, then guessCompare 3 thingsRecall: 3 questions · 8 cardsTypeScript · Go · Python

What you'll take away

  • Predict what prints first: the sync code, then every microtask, then the next task
  • Explain why setTimeout(fn, 0) runs after a promise's then, even once it's due
  • Fix a page a long loop freezes: split the work and yield, or move it to a Web Worker
  • Order process.nextTick, setImmediate and setTimeout 0 in a Node I/O callback

The 1-minute version

Tap a point and the picture below plays that step.

4Compare them all
The call stack does one thing at a timethe script runs · 0 ms (simulated)
The codeconsole.log("A")console.log("B")console.log("C")no line running
Call stackempty
Consolenothing yet
Microtask queuemicrotask
Task queuetask
Timers · Web APIstimers
The page
console.log("A") → …
Step 1 / 22 · step by step
0 msTime (simulated)
0On the call stack
0Microtasks waiting
0Tasks + timers waiting
0Printed

The event loop as one office: a worker at one desk (the call stack) does one job at a time, the printer is the console and the window is the page being drawn. Callbacks that wait are parcels in two lines: the microtasks beside the desk, the tasks out to the post office, where timers wait (steps 17–22 are Node.js). Times are the model's milliseconds, not real measurements. The order the model prints is checked against real runs on Node in the site's tests: every program in the "Watch" step, every set of up to 3 blocks, and 300 more random programs.

Step 4 · Every option at once, on one clock

Compare them all: Event loop

Every line is called from the same spot at the same time, and you watch whose callback gets to print first. Node: called from inside an I/O callback (where the order is fixed). Browser: there's no nextTick or setImmediate.

0.0 s
Node.jscalled inside readFile's callbackPrinted: nothing yet

Use it when nextTick when it has to run right after this code ends; setImmediate when waiting I/O should go first

Skip it when You rely on the order of setTimeout 0 and setImmediate outside an I/O callback: they can swap

Node's order matches what real Node prints (snippets/event-loop/race.ts and the site's tests). ? = the order of setTimeout and requestAnimationFrame isn't fixed: it depends on where in the frame the code ran. Press any tile to see it large above, with when it fits.

What the event loop does

JavaScript runs on one thread with one call stack: it does one thing at a time, until it's done. Work that has to wait (timers, the network, reading a file) doesn't wait inside JavaScript. It's handed to the host (the browser or Node) to wait on instead, and when it's done, the callback is put in a queue. The event loop is the loop that takes work from the queues and puts it on the stack every time the stack is empty.

Every round goes like this

  • Run one task to the end: the whole script is the first task
  • Empty the microtask queue, including any added along the way
  • Draw the screen if a frame is due (requestAnimationFrame runs here, before drawing)
  • Pick the next task and go round again

What goes in which queue

Where it comes fromQueue
setTimeout, setIntervala task, once the time is up
click, message, I/Otask
then / catch / finally, the part after awaitmicrotask
queueMicrotaskmicrotask
requestAnimationFramebefore the next frame is drawn

Heavy work freezes the page

While the stack isn't empty, nothing can cut in: clicks get no answer, animations stop, timers run late. The way out is to split the work into small chunks and hand control back to the loop between them, for example await new Promise((r) => setTimeout(r)), or move it to a Web Worker (in Node: worker_threads). await Promise.resolve() doesn't help, because it's still a microtask: the screen still hasn't been drawn.

Waiting work overlaps on one thread; crunching needs more cores. Both on one timeline: Concurrency vs parallelism.

Node.js

Node uses libuv, which goes round in phases: timers → pending callbacks → poll (waiting for I/O) → check (setImmediate) → close callbacks. process.nextTick and microtasks run every time a callback ends, before the next callback. File work happens in libuv's thread pool, but the callbacks still come back to run on JavaScript's one thread.

In other languages

Python's asyncio has a real event loop, but with a single first-come, first-served queue and no separate microtasks. time.sleep() or CPU work blocks the whole loop, just like in JavaScript, so you need await asyncio.sleep(). Go has no event loop like this: the runtime's scheduler spreads goroutines over several threads, and work that hangs or eats CPU only holds up its own goroutine.

In real code

order.ts
// Which line prints first? Synchronous code, then every microtask, then the next task.
// Run: node order.ts   (Node 23.6+; on Node 22: node --experimental-strip-types order.ts)
import assert from "node:assert/strict";

const printed: string[] = [];
const log = (line: string) => {
  printed.push(line);
  console.log(line);
};

log("A sync");
setTimeout(() => log("F setTimeout 0 (a task)"), 0);
Promise.resolve().then(() => log("C then (a microtask)"));
queueMicrotask(() => log("D queueMicrotask (a microtask)"));
(async () => {
  await null; // the rest of this function waits in the microtask queue
  log("E after await (a microtask)");
})();
const start = Date.now();
while (Date.now() - start < 50) {} // 50 ms of CPU: nothing else can run meanwhile, not even the timer
log("B sync, after 50 ms of CPU");

setTimeout(() => assert.deepEqual(printed.map((line) => line[0]), ["A", "B", "C", "D", "E", "F"]), 10);
Run: node order.ts (Node 23.6+ · on Node 22 add --experimental-strip-types)It printed:
A sync
B sync, after 50 ms of CPU
C then (a microtask)
D queueMicrotask (a microtask)
E after await (a microtask)
F setTimeout 0 (a task)

TypeScript: plain lines first, then microtasks in the order they were queued, then the timer's task. Python: asyncio has a single queue with no separate microtasks, and a timer that comes due while a loop blocks joins the queue in the next round. Go: no event loop like JavaScript's. A slow goroutine doesn't block the others, and a fixed order comes from channels waiting on each other.

Common questions

JavaScript is single-threaded. How does it do several things at once?

Your code runs on one thread with one call stack. Waiting (timers, the network, files) is handed to the browser or Node, and the callback comes back through a queue when it's done. So the waiting overlaps; running code still happens one thing at a time.

Read: what the event loop does

Why doesn't setTimeout(fn, 0) run right away?

0 means as soon as possible, not now. The callback joins the task queue and waits until the stack is empty and the microtasks are done, so the rest of your code and every promise callback go first.

A promise's then or setTimeout 0: which runs first?

The then. It's a microtask, and the whole microtask queue is emptied before the next task is picked, so even a timer that's already due has to wait.

What's the difference between a task and a microtask?

Tasks are timers, clicks, messages and I/O, one per round. Microtasks are then, catch, finally, the part after await and queueMicrotask, and the whole queue runs after each task, before the screen is drawn.

Table: what goes in which queue

A heavy loop freezes my page. How do I fix it?

Split the work into small chunks and give the loop a turn between them, for example await new Promise((r) => setTimeout(r)), or move it to a Web Worker. await Promise.resolve() doesn't help: it's still a microtask, so the screen still isn't drawn.

In Node, how do process.nextTick and setImmediate differ?

process.nextTick runs as soon as the current callback ends, before the next one. setImmediate waits for the check phase, after Node has polled for I/O. Outside an I/O callback, setTimeout(fn, 0) and setImmediate can come in either order, so don't rely on it.

Does Python's asyncio work the same way?

It has a real event loop too, but one first-come, first-served queue and no separate microtasks. time.sleep() or CPU work blocks the whole loop, as in JavaScript, so you await asyncio.sleep(). Go has no loop like this: goroutines are spread over several threads.

Read: in other languages

Next lesson

Sync vs asyncLevel: Intermediate

One thread holding many waits is how a server serves many requests; next, a thread each, a pool and an event loop on the same load.