Lesson 2 · The web platform, in depth
The event loop
Tasks, microtasks and rendering: predict exactly when your code runs.
About 25 minutes
Tab indents. Press Escape, then Tab, to leave the editor.
A browser tab runs your JavaScript, its event handlers, its promise callbacks and its rendering on one main thread, coordinated by the event loop defined in the HTML standard. If you know the processing model precisely you can predict the order of any snippet, explain why a UI freezes while "async" code runs, and choose the right primitive to yield. This lesson is the model, in the order the spec runs it.
One turn of the loop
Each iteration of the event loop does, roughly:
- Pick a task. Choose one runnable task from one of the task queues and run it to completion. Which queue is implementation-defined: browsers keep separate queues per task source (timers, user input, networking,
postMessage…) and may prioritize, for example, input over timers. Within one source, order is first in, first out. - Microtask checkpoint. Run every microtask in the microtask queue, including microtasks queued by microtasks, until it's empty.
- Update the rendering, if this is a rendering opportunity (usually aligned to the display's refresh, skipped when nothing changed or the page is hidden): run resize and scroll steps, evaluate media queries, update animations, run
requestAnimationFramecallbacks, recalculate style and layout, deliverResizeObservernotifications, updateIntersectionObserverobservations, then paint.
Then back to step 1. The consequences:
- A task can't be interrupted. A 300 ms task is 300 ms with no input handling and no frames.
- Microtasks run before the browser gets control back. A microtask that queues another microtask, forever, freezes the page as hard as
while (true) {}. - Rendering happens between tasks, at most once per frame. Ten DOM writes in one task produce one frame.
What's a task, what's a microtask
| Queues a task | Queues a microtask | Runs in the rendering step |
|---|---|---|
setTimeout, setInterval | promise.then/catch/finally callbacks | requestAnimationFrame |
User input events (click, keydown…) | Continuation after await | ResizeObserver callbacks |
MessageChannel / postMessage | queueMicrotask(fn) | IntersectionObserver callbacks (queued as a task from this step) |
Network events, XMLHttpRequest callbacks | MutationObserver callbacks | |
scheduler.postTask() (where supported) |
Details that matter when you predict an order:
Promise.resolve().then(f)queuesfimmediately, because the promise is already settled..then(g)chained after it queuesgonly whenf's promise settles, so it goes to the back of the queue at that point.await vsuspends the async function and queues its continuation as a microtask oncevsettles. For a native promise or a plain value that costs one microtask turn. The code before the firstawaitruns synchronously, inside the caller.setTimeout(f, 0)is a request for "a task, no sooner than 0 ms". Once timers nest more than five levels deep, the spec clamps the delay to at least 4 ms. Background tabs throttle timers much harder.setTimeoutversusrequestAnimationFramehas no fixed order. Whether the timer task runs before or after the next rendering opportunity depends on where in the frame you are.
Lab
Event loop visualizer
Predict the console output, then step through to see why it comes out in that order.
1console.log('A')2setTimeout(() => {3 console.log('B')4}, 0)5console.log('C')
- run script
The whole script runs as one task. The event loop takes it from the task queue and starts it.
Predict it
Challenge
Predict the log order
Read the program, then fill in prediction with the eight labels in the order they will be logged. Don't press Run until you've committed to an answer: the console will give it away.
- Nothing logged yet.
- Your prediction lists each of the eight labels exactly once
- Your prediction matches what the program actually logs
Walk through it: when the script ends, the microtask queue is [then A, microtask, after await]. Running then A settles its promise, which queues then B at the back: [microtask, after await, then B]. Only once the queue is empty does the loop take the next task, the timer.
Microtasks between event listeners
The microtask checkpoint isn't only at the end of a task. The spec performs one whenever a callback returns and the JavaScript stack is empty, so microtasks also run between event listeners, between requestAnimationFrame callbacks, and between observer callbacks. The "stack is empty" condition creates a classic trap:
button.addEventListener('click', () => {
queueMicrotask(() => console.log('micro'))
console.log('listener 1')
})
button.addEventListener('click', () => console.log('listener 2'))
Yielding: why await doesn't help a long task
Splitting work into an async function doesn't make it yield. await Promise.resolve() queues a microtask, and microtasks run before the loop goes back for another task or a frame. To let input and rendering in, you need to end the current task and continue in a new one.
| Primitive | Yields to | Notes |
|---|---|---|
await Promise.resolve() | nothing | Microtask: same turn of the loop |
setTimeout(resolve, 0) | other tasks and rendering | Clamped to ≥ 4 ms after five levels of nesting; throttled in background tabs |
MessageChannel message | other tasks and rendering | No clamping; a common polyfill for "next task" |
requestAnimationFrame | rendering | Runs before paint, once per frame; doesn't run while hidden. Good for visual work, not for chunking computation |
scheduler.yield() | other tasks and rendering | Continuation is prioritized ahead of other queued tasks of the same priority. Not in every engine yet: feature-detect globalThis.scheduler?.yield |
Challenge
Actually yield
processInChunks(items, chunkSize, handleChunk) calls handleChunk once per chunk, in order, and returns a promise that resolves after the last chunk. The starter "yields" with await Promise.resolve(). Press Run, then Start: the progress text jumps straight to 100% because the page never renders mid-way.
Make it yield to the event loop between chunks so other tasks (a timer, a click) and rendering can run. Use a task-based yield (setTimeout or MessageChannel) wrapped in a promise.
- Nothing logged yet.
- Every item is handled once, in order, in chunks of the right size
- A timer queued while it's working gets to run before the last chunk
Notice the spinner: it's a transform animation, so the compositor keeps it turning even while the starter version blocks the main thread. The progress text, which needs main-thread rendering, is what freezes. In production, prefer scheduler.yield() where it exists (it resumes your work ahead of other queued tasks, so a long job isn't starved by everything else) and fall back to a task-based yield elsewhere. Yield on a time budget (say every few milliseconds of work, checked with performance.now()) rather than every N items, since item cost varies.
Using the model on real bugs
A CSS transition that doesn't play. You append an element and immediately add the class that changes its opacity, and it appears at full opacity with no fade. Both changes happened in one task, so the first style calculation already sees the final value: there was never a "before" style to transition from. Fix it by giving the browser a style computation in between. Either force one synchronously (el.getBoundingClientRect() or getComputedStyle(el).opacity after appending), or add the class in a later frame. One requestAnimationFrame isn't enough, because rAF callbacks run before that frame's style calculation; the common idiom nests two:
list.append(toast)
requestAnimationFrame(() => {
requestAnimationFrame(() => toast.classList.add('visible')) // next frame: start style exists
})
A promise loop that freezes the tab. A recursive function that processes a queue with .then(next) or await and no task boundary never lets the loop reach rendering or input, however "asynchronous" it looks. The DevTools Performance panel shows it as one enormous task full of tiny microtask slices. The fix is the yield from the previous section.
Order-dependent tests. A test that clicks with el.click() and asserts synchronously, or that relies on setTimeout(0) running before a promise chain finishes, is encoding event-loop details. Await the specific thing you depend on (the promise, an event, requestAnimationFrame when you need a frame) rather than sleeping.
Where the model leaks
- Node.js has its own loop (libuv phases: timers, poll, check…),
process.nextTickruns before promise microtasks, andsetImmediateversussetTimeout(0)ordering depends on the phase you're in. Don't port browser intuitions blindly. - Workers have their own event loop and no rendering step. Moving CPU-heavy work (parsing, search indexing, image decoding) to a worker is the only way to make it not compete with input at all.
- Hidden pages get no rendering opportunities, so
requestAnimationFramestops entirely, and timers are throttled. Never drive state that must progress (a sync, a save) from rAF.
Recap
- One loop turn: run one task to completion, drain the microtask queue completely, then maybe render (rAF → style/layout → ResizeObserver → IntersectionObserver → paint).
- Promise callbacks,
awaitcontinuations,queueMicrotaskandMutationObserverare microtasks; timers, input events andMessageChannelare tasks. - Microtasks also run between listeners when the stack is empty, which is why real clicks and
el.click()can order differently. awaitdoesn't yield. To let input and frames in, end the task:scheduler.yield()where available, otherwisesetTimeoutorMessageChannel, or move the work to a worker.
Finished this lesson?
Mark it complete to track your progress on this device.