JavaScript · Lesson 12
The Event Loop
How JavaScript runs one piece of code at a time on one thread, and still handles timers, promises, clicks and network responses, plus why order surprises people, how await splits a function, and how to keep long work from freezing the page.
In short
- One thread: code runs to completion
- Tasks one at a time; all microtasks after each
awaitpauses and resumes as a microtask- Yield with a new task to keep the page responsive
- Node adds
nextTickandsetImmediate
JavaScript runs your code on one thread. There is never a second piece of your JavaScript running at the same moment. Yet a page handles clicks while it waits for the network, and a Node server handles thousands of requests at once. The event loop is how: it's the small scheduler that decides which waiting callback runs next.
You can write a lot of JavaScript without thinking about it. Then one day a log comes out in the "wrong" order, a state update "hasn't happened yet", a timer fires late, or the page freezes during a big loop. All of those make sense once you have the right picture. That picture is small: one call stack and two queues.
Every js snippet below has a ▶ Try button. Predict the output first, then run it. The playground
waits for pending timers before it stops, like Node does before exiting.
One thread, one call stack
When a function calls another function, the engine pushes a frame onto the call stack. When it returns, the frame is popped. The stack is "where we are right now". With one thread there is one stack, so exactly one function is running at any moment.
The most important consequence is run to completion: once a piece of JavaScript starts, nothing interrupts it. Not a timer, not a click, not a network response. They all wait until the stack is empty.
const start = Date.now();
setTimeout(() => console.log(`timer asked for 0 ms, ran after ${Date.now() - start} ms`), 0);
// 50 ms of busy work. Nothing else can run until this loop finishes.
while (Date.now() - start < 50) {}
console.log('loop done');
The timer was ready almost at once, but it had to wait for the loop. That's the whole story of a frozen page: some code is holding the only thread.
Who does the waiting?
If there's only one thread, who counts down the timer and waits for the network? The host: the
browser or Node. setTimeout, fetch and file reads are not part of the JavaScript language itself.
They're host APIs. Your code asks the host to start something and gives it a callback. The host does the
waiting (on its own threads, or with the operating system), and when the result is ready it puts your
callback in a queue. The event loop takes callbacks from the queues and runs them on the one
JavaScript thread, one at a time.
So "async" in JavaScript never means "runs at the same time as my code". It means "runs later, when the thread is free".
Two queues: tasks and microtasks
There are two kinds of queued work, and the difference explains almost every ordering puzzle.
| Queue | What goes in | When it runs |
|---|---|---|
| Task queue (also called macrotasks) | timer callbacks (setTimeout, setInterval), events such as clicks and key presses, network and file I/O callbacks, MessageChannel messages | one task per turn of the loop |
| Microtask queue | promise callbacks (then, catch, finally), the rest of an async function after await, queueMicrotask(fn) | after the current task, until the queue is empty |
One turn of the loop looks like this:
forever:
1. take the oldest task that is ready, and run it to completion
2. run every microtask, including microtasks queued by microtasks, until none are left
3. (browser) if it's time for a new frame: requestAnimationFrame callbacks, then style, layout, paint
Your script itself is the first task. So when the script finishes, the microtasks run, and only then does the first timer get a turn:
console.log('1: script (a task)');
setTimeout(() => console.log('4: timer (the next task)'), 0);
Promise.resolve().then(() => console.log('3: promise callback (a microtask)'));
console.log('2: script again');
That's why setTimeout(fn, 0) always runs after promise callbacks queued at the same time. A delay of
0 means "as soon as possible, as a new task", and the current task's microtasks always come first.
Microtasks drain completely, tasks don't
Microtasks queued while the microtask queue is draining run in the same drain. Tasks queued by a task always wait for a later turn. Watch where the timers and promise callbacks land here:
setTimeout(() => {
console.log('timer 1');
Promise.resolve().then(() => console.log(' microtask from timer 1'));
}, 0);
setTimeout(() => console.log('timer 2'), 0);
Promise.resolve()
.then(() => {
console.log('microtask A');
queueMicrotask(() => console.log('microtask C, queued by A'));
})
.then(() => console.log('microtask B (the next then in the chain)'));
Read the output carefully:
- Both microtasks queued during the script, and the one queued by
A, run before any timer. - Each
thenin a chain is its own microtask, queued only when the previous step finishes. SoC(queued insideA) runs beforeB. - After
timer 1(a task), the loop drains microtasks again, so its microtask runs beforetimer 2.
queueMicrotask
queueMicrotask(fn) puts fn straight into the microtask queue, without creating a promise. Use it when
you want "after the current code, but before anything else gets a turn": for example, to batch several
calls made in the same tick into one update. Two of this topic's exercises use it.
const pending = [];
function logLater(message) {
if (pending.length === 0) queueMicrotask(flush); // first call in this tick schedules one flush
pending.push(message);
}
function flush() {
console.log(`flushing ${pending.length} messages: ${pending.join(', ')}`);
pending.length = 0;
}
logLater('a');
logLater('b');
logLater('c');
console.log('end of script');
Timers are "no sooner than"
setTimeout(fn, ms) means: after at least ms milliseconds, put fn in the task queue. It can run
later, because:
- the thread may be busy (as in the first example),
- other tasks may be ahead of it in the queue,
- browsers clamp nested timers (a timer set inside a timer, five levels deep) to at least 4 ms,
- browsers throttle timers in background tabs to about once a second, or less.
Timers with the same delay run in the order you created them. setInterval doesn't wait for your
callback, so a slow callback makes runs pile up. A setTimeout that schedules the next one at the end of
each run waits for the previous run to finish, which is usually what you want for polling.
How await splits a function
An async function runs synchronously until its first await. At the await, it returns to its
caller. The rest of the function becomes a callback that runs as a microtask when the awaited promise
settles, even when the value isn't a promise at all.
So this:
async function load() {
console.log('B: before await');
const value = await 42;
console.log('D: after await, got', value);
}
console.log('A');
load();
console.log('C: the caller carries on');
behaves like this hand-written version:
function load() {
console.log('B: before await');
return Promise.resolve(42).then((value) => {
console.log('D: after await, got', value);
});
}
console.log('A');
load();
console.log('C: the caller carries on');
Every await is a point where other code can run. Two async functions called one after the other
interleave at their awaits:
async function worker(name, steps) {
for (let i = 1; i <= steps; i++) {
console.log(`${name} step ${i}`);
await null; // give everyone else a turn
}
}
worker('A', 3);
worker('B', 2);
console.log('both started');
This is why JavaScript doesn't need locks for count++, but async code can still have race
conditions: between two awaits, other code may have changed the state you read before the first one.
A search box that shows the response of an old query, because it arrived after the newer one, is the
classic example.
Microtask starvation
The loop only takes the next task when the microtask queue is empty. Microtasks that keep queueing more microtasks keep everything else waiting: timers, clicks, rendering.
let ticks = 0;
setTimeout(() => console.log(`the timer finally ran, after ${ticks} microtasks`), 0);
function spin() {
ticks++;
if (ticks < 100000) queueMicrotask(spin); // without a limit, the timer would never run
}
spin();
In a browser, a microtask loop without a limit freezes the page just like while (true) {}. It also means
await Promise.resolve() does not let the page breathe. It only lets other microtasks run. To let
timers, input and rendering in, you need a new task.
Don't block the loop
Long synchronous work holds the thread. In a browser, nothing responds: no clicks, no typing, no animation. On a Node server, every request waits, not just the one doing the work. Browsers call any task over 50 ms a long task, and it shows up as bad responsiveness (the INP metric).
The fix for work you can't avoid is to split it into chunks and give the loop a turn between them.
A chunk ends after a time budget, and setTimeout(resolve, 0) gives you a new task:
const yieldToLoop = () => new Promise((resolve) => setTimeout(resolve, 0));
async function sumInChunks(n, budgetMs = 10) {
let total = 0;
let sliceStart = performance.now();
for (let i = 0; i < n; i++) {
total += Math.sqrt(i);
// Checking the clock costs time too, so only check every 1,000 items.
if (i % 1000 === 0 && performance.now() - sliceStart > budgetMs) {
await yieldToLoop(); // other tasks (clicks, timers, rendering) run here
sliceStart = performance.now();
}
}
return total;
}
const started = performance.now();
let timerRanAt = null;
setTimeout(() => (timerRanAt = Math.round(performance.now() - started)), 0);
sumInChunks(5_000_000).then((total) => {
console.log('total', Math.round(total));
console.log(`a timer still got to run part-way through, after ~${timerRanAt} ms`);
});
Options, from simplest to strongest:
setTimeout(fn, 0)gives a new task. Simple, but nested timers are clamped to 4 ms in browsers.MessageChannel(post a message to yourself) gives a new task without the clamp. React's scheduler uses this in browsers.scheduler.yield()yields and puts your continuation ahead of other ordinary tasks. Chromium-based browsers and Firefox (142+) have it; Safari doesn't yet. Check for it and fall back to one of the above.- A Web Worker (browser) or
worker_threads(Node) runs the work on another thread, with its own event loop, and talks to yours with messages. This is real parallelism, and the right answer for heavy work such as parsing large files, image processing or crypto.
Rendering and requestAnimationFrame
In a browser, the page is painted between tasks, at most once per frame (about every 16 ms on a 60 Hz screen). While your code runs, the screen can't update. If you change the DOM ten times in one task, the user only ever sees the last version.
requestAnimationFrame(fn) runs fn just before the next paint. That's the right place for visual
updates and animations: it runs once per frame, in step with the screen, and browsers pause it in
background tabs.
// Browser only (not runnable here): move a box 2px per frame.
const box = document.querySelector('.box');
let x = 0;
function frame() {
x += 2;
box.style.transform = `translateX(${x}px)`;
if (x < 300) requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
Things worth knowing:
- A
setTimeoutanimation drifts out of step with the screen and can update twice in one frame, or not at all in another.requestAnimationFramedoesn't. - Microtasks run before the browser paints, so a promise callback can't "show" an intermediate state either. To let a loading spinner appear before heavy work starts, yield a task (or two frames) first.
- Reading layout (
offsetHeight,getBoundingClientRect) right after changing styles forces the browser to compute layout immediately, in the middle of your task. Doing that in a loop ("layout thrashing") is a classic performance bug.
Where Node differs
Node uses the same model (tasks, microtasks, run to completion) with a few extras:
process.nextTick(fn)has its own queue. In a CommonJS file it runs before promise microtasks. In an ES module, the module body itself runs as a microtask, so promise callbacks queued at the top level run first. It predates promises. PreferqueueMicrotaskin new code.setImmediate(fn)runs in a "check" phase right after I/O callbacks. Inside an I/O callback, it always runs before asetTimeout(fn, 0). At the top level of a script, their order isn't guaranteed.- Node's loop has phases (timers, I/O polling, check, close callbacks). For everyday code, "one task, then all microtasks" is still the right model.
- Since Node 11, microtasks run after each timer callback, as in browsers. Older versions ran all due timers first, so very old blog posts show different output.
// Node only (not runnable here)
setTimeout(() => console.log('timeout'), 0);
setImmediate(() => console.log('immediate'));
Promise.resolve().then(() => console.log('promise'));
process.nextTick(() => console.log('nextTick'));
// CommonJS: nextTick, promise, then timeout and immediate in either order
// (an ES module prints promise before nextTick)
This lab runs your code in a worker that both browsers and Node support, so exercises stick to
setTimeout, promises and queueMicrotask.
Coming from C#
Side note
- .NET has a thread pool:
awaitfrees the thread, and the continuation may run on another thread, possibly at the same time as other code. In JavaScript, every continuation runs on the same thread, one at a time. There are no locks, noInterlocked, and no data races on plain variables. - The closest .NET picture is a UI thread with a
SynchronizationContext(WinForms, WPF): continuations are posted back to one thread. JavaScript is like that everywhere. Task.Run(move CPU work to another thread) has no direct equivalent. The JavaScript answer is a worker (Web Worker,worker_threads) or a separate service.- Blocking calls such as
Thread.Sleepor.Resultdon't exist. You can't block on a promise, onlyawaitit. A busywhileloop is the only way to block, and it blocks everything.
In real codebases
Side note
- React batches state updates made in the same task into one render (since React 18), and its
scheduler slices rendering work into short chunks and yields to the browser between them. That's how
startTransitionkeeps typing responsive. - Vue's
nextTick, Lit and Svelte queue DOM updates as a microtask: change ten properties and the DOM updates once. - Angular used zone.js to patch
setTimeout, promises and events, so it could run change detection after every task. Zoneless Angular (the default for new apps since v21) uses signals instead. - GraphQL DataLoader collects every
load(id)made in the same tick and sends one batched query. The exercises build a small version. - Node servers stay fast by keeping each request's synchronous work short. A slow regex, a huge
JSON.parse, or a synchronous file read in a request handler slows down every request, not just one. Tools likeclinicand the--cpu-profflag find these. - Tests: fake timers (
vi.useFakeTimers(),jest.useFakeTimers()) replace the timer task queue, so tests can jump ahead in time. Angular'sfakeAsyncandflushdo the same.
The exercises
- soon and later (easy): run a function as a microtask or as a new task, and cancel it.
- A cancellable sleep (easy): a timer you can stop, that cleans up after itself.
- A batching store (medium): many updates in one tick, one notification.
- Polling without overlap (medium): a self-scheduling loop that
setIntervalcan't give you. - A priority task queue (medium): one task per turn of the loop, most urgent first.
- A batching loader (hard): DataLoader's trick, collecting
load(key)calls into one request per tick. - Time-sliced work (hard): run a generator in short slices, yielding to the loop between them.
Practise this lesson
In the app: a short video, 7 exercises checked by real tests and a 12-question concept check. Free with a GitHub account.
Open in the app