← Back to JavaScript, page 8

javascript-0149 · Medium mid

What is requestAnimationFrame, why is it better than setTimeout for animation, and how do you use it correctly?

requestAnimationFrame schedules a callback to run right before the browser's next repaint, usually 60 times per second, and passes a high-resolution timestamp. It syncs visual updates with the display, pauses in background tabs, and avoids wasted work. Drive animations from the timestamp instead of counting frames, cancel with cancelAnimationFrame, and use it to batch DOM writes and throttle scroll handlers.

Full answer

Screens refresh at a fixed rate (60, 120, or more times per second). To look smooth, visual changes should happen once per frame, just before the browser paints. setTimeout(fn, 16) is not tied to that: it can run at any point in the frame, drift, and run in a hidden tab, which wastes power, and it may cause skipped or doubled frames.

requestAnimationFrame(callback) asks the browser to call callback(timestamp) once, before the next repaint. The timestamp is a DOMHighResTimeStamp in milliseconds, the same time base as performance.now(). To animate, call requestAnimationFrame again from inside the callback. It returns an id for cancelAnimationFrame(id). Browsers pause callbacks in background tabs, which saves battery and CPU.

Correct use:

  • Use time, not frame counts. A 120 Hz screen calls twice as often as a 60 Hz one. Compute progress as (timestamp - start) / duration, clamp it to 1, apply an easing function, and stop when it reaches 1. Then the animation takes the same time on every display.
  • Do small work. A callback that takes more than a few milliseconds causes dropped frames. Move heavy work to a Worker, or split it.
  • Batch DOM reads and writes. Reading layout properties (such as offsetWidth) after a write forces an early layout (layout thrashing). Read everything first, then write in the frame.
  • Throttle event handlers: events like scroll, resize, and mousemove can fire many times per frame. Store the latest value in the handler and schedule one requestAnimationFrame callback if none is pending.
  • Cancel when the component unmounts or the animation is replaced.

Alternatives: CSS transitions, animations, and the Web Animations API run on the compositor for properties like transform and opacity, and are smoother than JavaScript for simple effects. Use requestAnimationFrame when logic must run each frame (games, canvas drawing, physics, scroll-linked effects). For work that can wait, requestIdleCallback runs when the main thread is idle.

Order: promise callbacks (microtasks) run before the next animation frame callback, which runs before the paint.

javascript
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const easeOut = (t) => 1 - (1 - t) ** 3;

// 1. Time-based animation: the result does not depend on how many frames ran
function animate({ from, to, duration, onFrame }) {
  return new Promise((resolve) => {
    let start;
    let frames = 0;
    let lastTimestamp = -Infinity;
    let monotonic = true;
    function step(timestamp) {
      start ??= timestamp;
      frames++;
      if (timestamp < lastTimestamp) monotonic = false;
      lastTimestamp = timestamp;
      const progress = Math.min(1, (timestamp - start) / duration);
      onFrame(from + (to - from) * easeOut(progress));
      if (progress < 1) requestAnimationFrame(step);
      else resolve({ frames, monotonic, elapsed: timestamp - start });
    }
    requestAnimationFrame(step);
  });
}

// 2. Throttle many events into one frame
function rafThrottle(fn) {
  let pending = false;
  let latestArgs;
  return (...args) => {
    latestArgs = args;
    if (pending) return;
    pending = true;
    requestAnimationFrame(() => {
      pending = false;
      fn(...latestArgs);
    });
  };
}

async function main() {
  const values = [];
  const result = await animate({ from: 0, to: 100, duration: 100, onFrame: (v) => values.push(v) });
  console.log('final value is exactly the target:', values.at(-1) === 100);
  console.log('several frames ran:', result.frames > 1, '| timestamps never go backward:', result.monotonic, '| lasted at least the duration:', result.elapsed >= 100);
  console.log('eased values only go up:', values.every((v, i) => i === 0 || v >= values[i - 1]));

  let handled = 0;
  let lastSeen;
  const onScroll = rafThrottle((position) => { handled++; lastSeen = position; });
  for (let position = 1; position <= 100; position++) onScroll(position);
  console.log('100 events so far, handler runs before the frame:', handled);
  await wait(60);
  console.log('after a frame: handler ran', handled, 'time(s) with the latest value', lastSeen);

  let cancelledRan = false;
  const id = requestAnimationFrame(() => { cancelledRan = true; });
  cancelAnimationFrame(id);
  await wait(60);
  console.log('cancelled callback ran:', cancelledRan);

  const order = [];
  requestAnimationFrame(() => order.push('animation frame'));
  Promise.resolve().then(() => order.push('promise microtask'));
  order.push('synchronous code');
  await wait(60);
  console.log(order);
}
main();

Written for a browser console or script tag; checked here with Node.js v24.22.1 and jsdom, two runs with identical output. Output: final value is exactly the target: true several frames ran: true | timestamps never go backward: true | lasted at least the duration: true eased values only go up: true 100 events so far, handler runs before the frame: 0 after a frame: handler ran 1 time(s) with the latest value 100 cancelled callback ran: false [ 'synchronous code', 'promise microtask', 'animation frame' ]

Key points

  • requestAnimationFrame runs a callback before the next repaint with a high-resolution timestamp.
  • It matches display refresh, pauses in background tabs, and avoids wasted work compared with setTimeout.
  • Drive animations by elapsed time, not by frame count, and clamp progress to 1.
  • Batch reads before writes, keep callbacks short, and cancel when done.
  • Throttle scroll and resize handlers with a single pending frame; prefer CSS animations for simple effects.

Common mistakes

  • Counting frames for animation duration, so speed depends on the display rate.
  • Mixing layout reads and writes inside the frame and causing layout thrashing.
  • Forgetting cancelAnimationFrame when the animation is replaced or the component is removed.
  • Doing heavy work in the callback and dropping frames.

Follow-ups

  • How does the Web Animations API or a CSS transition compare with requestAnimationFrame?
  • What is layout thrashing and how do you avoid it?
  • When would you use requestIdleCallback instead?

Tips

  • Say what it syncs with: the next repaint.
  • Show progress based on timestamps and clamp it.
  • Mention throttling event handlers and cancellation.