Skip to content
jshacks.dev
Async

requestAnimationFrame and the Rendering Step

Learn when requestAnimationFrame callbacks run in the browser rendering step, why they beat timers for visual updates and how to avoid layout thrashing.

6 min read
Summarize in AI
Flat illustration of jobs on a conveyor heading to a rack of workers, with the JavaScript, Google Chrome, Redis and Node.js logos.

A browser does not repaint the page whenever your code changes something. It repaints on a schedule, usually once per display refresh, and requestAnimationFrame is the hook that lets your code run at exactly the right point in that schedule: after input events and timers have been handled, and just before the browser calculates styles, lays out the page and paints. Code that animates with setTimeout runs at a time the browser did not choose, and the result is dropped frames, wasted work for frames that are never shown and animations that keep running in a hidden tab. This post explains where requestAnimationFrame sits in the frame on current Chrome, Firefox and Safari, how to write a correct animation loop with a time delta, why reads and writes of layout must be separated, and what the callback does not do for you.

Where it sits in a frame

Each frame the browser works through a fixed sequence. Input events and other tasks run first. Then, if a rendering opportunity exists, the browser runs the animation frame callbacks, then recalculates styles, performs layout, paints and composites. The step order is defined by the HTML specification's "update the rendering" algorithm, and the point that matters is that requestAnimationFrame callbacks run before style and layout work, so anything you change inside one is picked up by the same frame's render.

A rendering opportunity occurs when the display is ready for a new frame, which on a 60 Hz screen is about every 16.7 ms and on a 120 Hz screen about every 8.3 ms. If nothing changed, the browser may skip the update entirely, and if the tab is hidden, rendering stops and your callbacks pause with it.

The basic call

requestAnimationFrame(callback) schedules one call for the next frame and returns a numeric id. The callback receives a high-resolution timestamp, in milliseconds, which is the same for every callback in that frame.

JavaScript
function onFrame(timestamp) {
  console.log("frame at", Math.round(timestamp), "ms");
}

const id = requestAnimationFrame(onFrame);
console.log("scheduled, id is a number:", typeof id === "number");
Text
scheduled, id is a number: true
frame at 1042 ms

The timestamp value varies on every run and depends on how long the page has been open, so the exact number is only an example. The callback ran once. To keep animating, you request the next frame from inside the callback, which is the loop shape every animation uses.

A loop that does not depend on the refresh rate

Moving an element by a fixed amount per frame makes the animation twice as fast on a 120 Hz screen as on a 60 Hz one. The fix is to move by an amount based on elapsed time.

JavaScript
const box = document.querySelector("#box");
const pixelsPerSecond = 240;

let x = 0;
let last;
let id;

function step(timestamp) {
  if (last === undefined) last = timestamp;

  const deltaSeconds = (timestamp - last) / 1000;
  last = timestamp;

  x = Math.min(x + pixelsPerSecond * deltaSeconds, 300);
  box.style.transform = `translateX(${x}px)`;

  if (x < 300) id = requestAnimationFrame(step);
}

id = requestAnimationFrame(step);
Text
(box slides from 0 to 300 px in about 1.25 s at any refresh rate)

The delta is the time since the previous frame, so a slow frame moves the box further and a fast one moves it less. The loop stops itself by not requesting another frame once the target is reached. Clamping with Math.min avoids overshoot on the final, possibly long, frame. To stop early, call cancelAnimationFrame(id).

Why not setTimeout

A timer fires when the timer fires, which has no relationship to when the screen refreshes. Three problems follow.

Missed or doubled frames. A 16 ms timer on a 60 Hz screen drifts against the refresh cycle, so some updates are painted late, and others happen twice before a paint and one is thrown away.

Work for nothing. Timers keep firing in background tabs, throttled but still running, while requestAnimationFrame stops entirely in a hidden tab, so a game or chart does not burn battery out of sight.

Mid-frame changes. A timer callback can run between an animation frame and the render step, forcing the browser to render a state you did not intend as a finished frame.

For one-off visual changes, the benefit is the same. If you must apply several style changes at the right moment, put them in a single requestAnimationFrame callback.

Layout thrashing

The most common performance bug around this API is interleaving reads and writes of layout. Reading a property such as offsetHeight or getBoundingClientRect() forces the browser to compute layout if any style is pending. Writing a style invalidates the layout again. A loop that alternates the two makes the browser recompute layout on every iteration.

JavaScript
const items = [...document.querySelectorAll(".item")];

// slow: read, write, read, write, ...
for (const item of items) {
  const width = item.offsetWidth;
  item.style.width = `${width + 10}px`;
}

// fast: all reads, then all writes
const widths = items.map((item) => item.offsetWidth);
items.forEach((item, i) => {
  item.style.width = `${widths[i] + 10}px`;
});
Text
(same final widths; the second version forces layout once instead of once per item)

Both versions produce the same widths, and the difference is the number of forced layouts. Putting the writes inside a requestAnimationFrame callback and the reads before it is a common way to organize the batches. Libraries that coordinate this, called schedulers or "fastdom" style helpers, queue reads and writes and flush them in the right order each frame.

Properties that are cheap to animate

Animating transform and opacity is cheap because browsers can handle them on the compositor, without redoing layout or paint. Animating width, height, top or left forces layout every frame. When you can express motion as a transform, do, and for simple cases prefer CSS transitions or the Web Animations API, which let the browser run the animation off the main thread. Use requestAnimationFrame where the animation needs your logic each frame, such as physics, a canvas drawing loop or a scrubbing control that follows the pointer.

Running something once, after the next paint

A common need is to run code after the browser has painted, such as measuring a transition's starting state. A single requestAnimationFrame runs before the paint, so people nest two of them.

JavaScript
function afterNextPaint(callback) {
  requestAnimationFrame(() => {
    requestAnimationFrame(callback);
  });
}

afterNextPaint(() => console.log("painted at least once"));
Text
painted at least once

The first callback runs before the upcoming paint, and the second runs in the following frame, which is after that paint. It is a pragmatic idiom, not a guarantee, but it holds in current browsers.

What it does not do

requestAnimationFrame does not make slow work fast. If your callback takes 30 ms, the frame is late, and the browser skips the ones you missed. Keep each callback short. It also does not run when the tab is hidden, which is a feature for animation and a problem for logic that must continue, such as a clock or a game server tick. Put logic that must keep running in a timer or a worker, and use the frame callback only to draw the latest state.

Finally, the timestamp is not the current time. It is the start time of the frame, so use performance.now() if you need the time at a later point in the callback.

Also inBrowser
Share

Keep reading

Flat illustration of a browser and a server trading a request and a response, with the Google Chrome, Swagger, Postman and NGINX logos.
Browser

The DOM Tree: Nodes, Elements and Text

Understand the DOM tree: node types, the difference between nodes and elements, text and comment nodes, tree navigation properties and how whitespace shows up.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.