← Back to JavaScript, page 9

javascript-0174 · Medium mid

Where does rendering fit into the browser event loop, and how do microtasks, timers, and requestAnimationFrame relate to a frame?

The browser runs one task, then all microtasks, and then it may run a rendering step if a frame is due, which includes requestAnimationFrame callbacks, style, layout, and paint. Microtasks always finish before the browser can paint, while timers are tasks that run between frames. A long task or an endless microtask chain blocks painting and input, so split work and yield.

Full answer

The browser's event loop repeats this cycle. Pick one task from a task queue (a click, a timer callback, a network event, a script). Run it to completion. Run all queued microtasks (promise callbacks and queueMicrotask) until the queue is empty. Then, if the browser decides a frame is due (typically every 16.7 ms at 60 Hz, and only when the page is visible), it runs the rendering steps: requestAnimationFrame callbacks, then style calculation, layout, and paint.

What follows from this:

  • Rendering cannot happen while JavaScript runs. A task that takes 200 ms blocks about 12 frames, input handling, and animations, which users feel as jank. Chrome reports tasks over 50 ms as long tasks.
  • Microtasks run before the next paint, so a state change made in a promise callback and another one made in the same task are painted together. An endless chain of microtasks starves rendering and timers.
  • setTimeout(fn, 0) queues a task. It runs after the current task and its microtasks, but the browser may or may not render in between, so it is not a promise of a frame. Timers also have a minimum delay (about 4 ms after nesting) and are clamped in background tabs.
  • requestAnimationFrame runs right before the next paint, which makes it the right place for visual updates such as reading layout and then writing styles, and for animation steps. Two updates in one frame are painted once.
  • Reading layout values (offsetHeight) after writing styles forces a synchronous layout, which is called layout thrashing. Batch reads before writes.
  • To keep the page responsive, split long work into chunks and yield between them. Options are setTimeout, scheduler.postTask or scheduler.yield where available, requestIdleCallback for low priority work, and Web Workers for heavy computation.
  • await of an already resolved value still yields only to the microtask queue, so it does not give the browser a chance to paint.

A common interview question: "Why does the loading text not appear before the loop starts?" Because the text change is only painted in the rendering step, which cannot happen until the synchronous loop and its microtasks have finished. Yield with a timer or a rAF plus a timer, then start the work.

javascript
// A small model of the loop, not a browser. It makes the order visible and repeatable.
function createLoop() {
  const tasks = [];
  const microtasks = [];
  const log = [];
  let frame = 0;
  const loop = {
    log,
    task: (name, fn) => tasks.push({ name, fn }),
    microtask: (fn) => microtasks.push(fn),
    raf: [],
    run(frameEveryNTasks) {
      let ran = 0;
      while (tasks.length) {
        const { name, fn } = tasks.shift();
        log.push('task ' + name);
        fn();
        while (microtasks.length) microtasks.shift()();
        ran++;
        if (ran % frameEveryNTasks === 0) {
          frame++;
          log.push(`--- frame ${frame}: rAF x${loop.raf.length}, then style, layout, paint`);
          const callbacks = loop.raf.splice(0);
          callbacks.forEach((cb) => cb());
        }
      }
    },
  };
  return loop;
}

const loop = createLoop();
loop.task('A (script)', () => {
  loop.log.push('  sync code in A');
  loop.microtask(() => loop.log.push('  microtask from A'));
  loop.raf.push(() => loop.log.push('  rAF callback'));
  loop.task('B (setTimeout 0)', () => {
    loop.log.push('  sync code in B');
    loop.microtask(() => loop.log.push('  microtask from B'));
  });
});
loop.task('C (click)', () => loop.log.push('  sync code in C'));
loop.run(2);
console.log(loop.log.join('\n'));

// The real engine proves the first part of the model: microtasks run before the next task.
const real = [];
setTimeout(() => real.push('timer task'), 0);
Promise.resolve().then(() => real.push('promise microtask'));
queueMicrotask(() => real.push('queueMicrotask'));
real.push('sync');
setTimeout(() => console.log('real engine order:', real.join(' > ')), 5);

Run with Node.js v24.22.1 as js-174.js; two runs gave identical output. Output: task A (script) sync code in A microtask from A task C (click) sync code in C --- frame 1: rAF x1, then style, layout, paint rAF callback task B (setTimeout 0) sync code in B microtask from B real engine order: sync > promise microtask > queueMicrotask > timer task

Key points

  • Cycle: one task, all microtasks, then possibly a render step with rAF, style, layout, and paint.
  • Nothing paints while JavaScript runs, so long tasks cause jank and unresponsive input.
  • Microtasks finish before paint; endless microtasks starve rendering and timers.
  • setTimeout 0 is a task, not a frame; use rAF for visual updates.
  • Chunk work and yield with timers, scheduler APIs, idle callbacks, or workers.

Common mistakes

  • Expecting the page to update during a long synchronous loop.
  • Using setTimeout 0 as if it guaranteed a repaint.
  • Doing visual updates in timers instead of requestAnimationFrame.
  • Alternating style writes and layout reads, which forces repeated layouts.

Follow-ups

  • How does scheduler.yield differ from setTimeout for splitting work?
  • Why can a promise chain block painting?
  • How do you find long tasks in a real page?

Tips

  • Draw the loop as task, microtasks, render.
  • Use the loading text example to show why yielding is needed.
  • Name rAF as the place for visual updates.