requestAnimationFrame — Web Animation

requestAnimationFrame(cb) (rAF) calls the function cb once only, right before the next frame, with that frame's timestamp (its time in ms, from the same clock…

When a guest switches from 2 nights to 3, the total on Mrs. Sri's card counts up from $70 to $105. A CSS transition can't do that: the number has to be calculated and written again as text on every frame. The tool for it is requestAnimationFrame (often shortened to rAF). With rAF, JavaScript tells the browser: "before you draw the next frame, run this function first".

Imagine you hand a note to the driver of a minibus that leaves the terminal every 16.7 ms: "before you leave, do this". The driver does it once, then writes down the departure time. Want it done on the next departure too? Hand over another note. If the terminal is closed, there are no departures, and your note waits.

In this picture, a departure is a frame (16.7 ms is the time between frames on a 60 Hz screen). Your note is the function you hand to rAF. The departure time is the timestamp, the record of that frame's time. A closed terminal is a tab that isn't visible.

One note, one frame

The simplest rAF loop: the function step writes the time of each frame to the console.

function step(timestamp) {
  console.log('frame at', timestamp);
  requestAnimationFrame(step); // hand over a note for the next frame
}

const id = requestAnimationFrame(step); // the first note

How many times per second? As many as the screen's refresh rate, when the browser doesn't limit it. We ran the same code on one of our laptops. Chromium and Firefox called step 120 times a second (8.3 ms apart), WebKit only 60 times (16.7 ms apart).

Compare this with setInterval(fn, 16), which runs fn every 16 ms. An interval follows the clock, not the frames. It can run twice in one frame or miss another, and it keeps running in a hidden tab. rAF always runs exactly once per frame that is drawn.

Count from time, not from the number of frames

Say the total has to rise by $35 in 300 ms. Some code adds $35 / 18 = $1.94 on every frame, because it assumes "300 ms = 18 frames", as on a 60 Hz screen (16.7 ms per frame). Take a guess first: on a laptop with a 120 Hz screen, how long does the count take? We measured that code and the "count from time" way on one laptop:

Add $1.94 per frame Count from time (300 ms)
WebKit 26.4, 60 Hz 18 frames, done at 303 ms 20 frames, done at 314 ms
Chromium 147, 120 Hz 18 frames, done at 150 ms 36 frames, done at 298 ms
Every frame 25 ms heavy 18 frames, done at 454 ms 13 frames, done at 336 ms

At 120 Hz the count takes 150 ms, twice as fast, because 18 frames at 120 Hz are only 18 × 8.3 ms. When every frame is heavy (a slow phone, a busy page), the opposite happens: the count takes longer, up to 454 ms. The "from time" version always ends at about 300 ms. Only its number of frames changes.

To count from time, turn the time that has passed (elapsedMs) into a progress t. The value t is the time that has passed divided by the duration: 0 at the start of the animation, 1 at the end. Then take the value between the start (from) and the target (to) that matches t:

function createAnimation(from, to, duration) {
  return {
    getValueAt(elapsedMs) {
      const t = Math.min(Math.max(elapsedMs / duration, 0), 1); // hold within 0..1
      return from + (to - from) * t;
    },
  };
}

Example createAnimation(0, 300, 1000), which goes from 0 to 300 in 1,000 ms:

elapsedMs t Value
0 0 0
500 0.5 150
1000 1 300
1500 1 (held) 300
-50 0 (held) 0

For motion that keeps going (physics, games), use the time between frames, called the delta time: dt = timestamp - previousTimestamp. Then x += speed * dt / 1000, with the speed in px per second. dt is in milliseconds, so you divide it by 1000 to get seconds.

Example: the total counting up

In JavaScript, an easing is just a function that turns t into a new t. One example is easeOutQuad(t) = t * (2 - t): it starts fast and then slows down, like ease-out. The function tweenTotal below uses it to write the new total into .total b on every frame:

const total = document.querySelector('.total b');
let frameId = 0;

function easeOutQuad(t) {
  return t * (2 - t); // same as 1 - (1 - t) * (1 - t)
}

function tweenTotal(from, to, duration = 300) {
  cancelAnimationFrame(frameId);        // stop a count that is still running
  let start = null;
  function step(now) {
    if (start === null) start = now;    // start time = the first frame
    const t = Math.min((now - start) / duration, 1);
    const value = from + (to - from) * easeOutQuad(t);
    total.textContent = '$' + Math.round(value).toLocaleString('en-US');
    if (t < 1) frameId = requestAnimationFrame(step);
  }
  frameId = requestAnimationFrame(step);
}

tweenTotal(70, 105); // from 2 nights to 3 nights
Time t easeOutQuad(t) Shown
0 ms 0 0 $70
75 ms 0.25 0.4375 $85
150 ms 0.5 0.75 $96
225 ms 0.75 0.9375 $103
300 ms 1 1 $105

Stopping a loop: cancelAnimationFrame

cancelAnimationFrame(id) cancels a note that hasn't run yet, so its callback is never called. Every call to requestAnimationFrame gives a new id. So keep the latest one, as frameId = requestAnimationFrame(step) does inside the tweenTotal loop.

Why does this matter? Say a guest clicks "3 nights" then "1 night" within 300 ms, and you don't cancel the first loop. Two loops run at the same time: on every frame two callbacks write the number, so the work is doubled. In React, cancel the loop in the effect's cleanup (the function that runs when the component is removed), so the loop stops with it.

When the tab or iframe isn't visible

When the tab is behind other tabs (document.visibilityState becomes 'hidden'), the browser stops calling rAF callbacks. According to MDN, most browsers do this to save battery. When the tab is opened again, the next timestamp jumps far ahead. A time-based count simply finishes at the final number, because t is held at 1. A physics loop with dt needs a limit, such as dt = Math.min(dt, 100), so objects don't jump far in a single frame.

In iframes (other pages placed inside your page), rAF is slowed down too, but differently in each browser. These are our measurements, in callbacks per second. "Other origin" means the iframe loads a page from another site:

Iframe Chromium 147 WebKit 26.4 Firefox 146
Other origin, off screen 0 0 1
Same origin, display: none 120 61 0

So never measure time by counting callbacks. Calculate it from the timestamp.

rAF or CSS / Web Animations API?

rAF is right for values you compute yourself every frame. Examples are drawing on a <canvas> (an element you draw on with JavaScript), physics (speed, bounces, friction), and values CSS can't express, like a number inside text or a scroll position.

For ordinary UI motion (transform, opacity), CSS or the Web Animations API is better. Remember the first lesson: with the main thread busy for 500 ms in the middle of an animation, a CSS transition and the Web Animations API still drew 60 frames each, rAF only 1. rAF always runs on the main thread, so it freezes with it.

⚠️ rAF loops that stop, run too fast, or pile up

TL;DR: requestAnimationFrame(cb) (rAF) calls the function cb once only, right before the next frame, with that frame's timestamp (its time in ms, from the same clock as performance.now()). To make a loop, call rAF again inside cb. Calculate from time, not from the number of frames. The progress t = Math.min(Math.max(elapsed / duration, 0), 1) is the time passed divided by the duration, held within 0 to 1. The animated value, from from to to, is from + (to - from) * t, and an easing such as easeOutQuad(t) = t * (2 - t) changes t (0.5 becomes 0.75). Code that adds to the value per frame (planned for 60 Hz) finishes a 300 ms animation in 150 ms on a 120 Hz screen. Keep the id from rAF and call cancelAnimationFrame(id) before starting again or when the element goes away. A hidden tab stops rAF. In iframes (pages inside a page), rAF is slowed down differently in each browser. Use rAF for canvas, physics and values CSS can't write (the total from $70 to $105). For transform and opacity, CSS or the Web Animations API keep running even when the main thread is busy.

⚡ One note, one frame

Write:

function step(timestamp) {
  console.log('frame at', timestamp);
  requestAnimationFrame(step); // hand over a note for the next frame
}

const id = requestAnimationFrame(step); // the first note

Meaning: requestAnimationFrame hands the function step to the browser like a note. The browser calls step once only, right before the next frame, with a timestamp (the time of that frame in milliseconds). To make a loop, step hands itself over again. The number of calls follows the screen's refresh rate: 120 times a second on a 120 Hz screen.

⚡ Count from time

Guess first: the total has to rise from $70 to $105 in 300 ms. Some code adds $1.94 on every frame, because it assumes "300 ms = 18 frames", as on a 60 Hz screen. On a 120 Hz laptop, how long does the count take?

150 ms, twice as fast, because 18 frames at 120 Hz are only 18 × 8.3 ms. When every frame is heavy, for example on a slow phone, the count takes longer instead, up to 454 ms.

Meaning: Don't add to the value per frame. Turn the time that has passed into a progress t: the time passed divided by the duration, 0 at the start and 1 at the end. Then calculate the value from t.

⚡ Hold it within 0 to 1

Write:

function createAnimation(from, to, duration) {
  return {
    getValueAt(elapsedMs) {
      const t = Math.min(Math.max(elapsedMs / duration, 0), 1); // hold within 0..1
      return from + (to - from) * t;
    },
  };
}

Meaning: For createAnimation(0, 300, 1000), from 0 to 300 in 1,000 ms, Math.min(..., 1) holds t at 1 or below. So at 1,500 ms the result stays 300, not 450. Math.max(..., 0) holds t at 0 or above, for negative time at the start: the first frame's timestamp is sometimes smaller than your start time.

⚡ A hidden tab stops rAF

Meaning: setInterval (which runs a function every few ms) keeps running in a hidden tab, but the browser stops calling the functions handed to rAF there, to save battery. Keep the id that requestAnimationFrame returns, then call cancelAnimationFrame(id) before you start the same animation again. Without it, the old loop and the new loop run at the same time and pile up.

What you will learn