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:

  1. 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.
  2. Microtask checkpoint. Run every microtask in the microtask queue, including microtasks queued by microtasks, until it's empty.
  3. 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 requestAnimationFrame callbacks, recalculate style and layout, deliver ResizeObserver notifications, update IntersectionObserver observations, 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 taskQueues a microtaskRuns in the rendering step
setTimeout, setIntervalpromise.then/catch/finally callbacksrequestAnimationFrame
User input events (click, keydown…)Continuation after awaitResizeObserver callbacks
MessageChannel / postMessagequeueMicrotask(fn)IntersectionObserver callbacks (queued as a task from this step)
Network events, XMLHttpRequest callbacksMutationObserver callbacks
scheduler.postTask() (where supported)

Details that matter when you predict an order:

  • Promise.resolve().then(f) queues f immediately, because the promise is already settled. .then(g) chained after it queues g only when f's promise settles, so it goes to the back of the queue at that point.
  • await v suspends the async function and queues its continuation as a microtask once v settles. For a native promise or a plain value that costs one microtask turn. The code before the first await runs 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.
  • setTimeout versus requestAnimationFrame has 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.

Program
1console.log('A')
2setTimeout(() => {
3 console.log('B')
4}, 0)
5console.log('C')
Console
    Call stack
      Timers
        Microtasks
          Tasks
          1. run script

          The whole script runs as one task. The event loop takes it from the task queue and starts it.

          1 / 7

          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.

          Console
          1. 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'))
          
          Question

          Quick check

          A user physically clicks the button, then later your test calls button.click() from a script. What does each log?
          Pick an answer.

          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.

          PrimitiveYields toNotes
          await Promise.resolve()nothingMicrotask: same turn of the loop
          setTimeout(resolve, 0)other tasks and renderingClamped to ≥ 4 ms after five levels of nesting; throttled in background tabs
          MessageChannel messageother tasks and renderingNo clamping; a common polyfill for "next task"
          requestAnimationFramerenderingRuns before paint, once per frame; doesn't run while hidden. Good for visual work, not for chunking computation
          scheduler.yield()other tasks and renderingContinuation 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.

          Console
          1. 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.nextTick runs before promise microtasks, and setImmediate versus setTimeout(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 requestAnimationFrame stops 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, await continuations, queueMicrotask and MutationObserver are microtasks; timers, input events and MessageChannel are tasks.
          • Microtasks also run between listeners when the stack is empty, which is why real clicks and el.click() can order differently.
          • await doesn't yield. To let input and frames in, end the task: scheduler.yield() where available, otherwise setTimeout or MessageChannel, or move the work to a worker.

          Finished this lesson?

          Mark it complete to track your progress on this device.