requestAnimationFrame — Performance

requestAnimationFrame(fn) calls fn right before the next frame is drawn, following the screen: about 60 times a second at 60 Hz, more at 120 Hz, and it stops…

A sliding box animation that takes exactly 1 second on your laptop finishes in half a second on your friend's new phone with a 120 Hz screen. Same code. The cause is in how the animation is scheduled and worked out.

requestAnimationFrame (often shortened to rAF) is how you tell the browser: "call this function right before you draw the next frame." A regular screen redraws 60 times a second, so one frame is about 16.7 ms. A 120 Hz screen draws 120 times a second. Picture a flipbook: the motion appears because each page is drawn a little differently and the pages are flipped at a steady beat. rAF makes sure you draw the next page right before it's flipped, not at some random moment.

How it works

const box = document.querySelector(".box");
let x = 0;

function frame() {
  x += 4;                                     // 4 px every frame
  box.style.transform = `translateX(${x}px)`;
  if (x < 240) requestAnimationFrame(frame);  // ask for the next frame
}

requestAnimationFrame(frame);

Why not setInterval

setInterval(fn, 16) runs on its own clock, no matter when the screen draws. Some frames get two updates, some get none, and the animation feels jerky.

setInterval(fn, 16) requestAnimationFrame(fn)
When it runs roughly every 16 ms, on its own clock right before a frame is drawn
On a 120 Hz screen still about 60 times a second 120 times a second
In a hidden tab keeps running, slowed to at most about once a second stops

Motion from time, not from the number of frames

The code in "How it works" moves 4 px every frame. On a 60 Hz screen, 240 px is 60 frames, so 1 second. On a 120 Hz screen, 60 frames are done in half a second. That's what happened on your friend's phone: half a second, twice as fast. On a busy phone that only manages to draw 30 frames a second, it becomes 2 seconds.

To keep the speed the same on any screen, work out the position from the time that has passed: progress = elapsedMs / duration, from 0 to 1. This is what the exercise is about:

function calculateAnimationProgress(startTime, currentTime, duration) {
  const elapsedMs = currentTime - startTime;
  const progress = Math.min(elapsedMs / duration, 1); // never more than 1
  return { progress, isComplete: progress >= 1, elapsedMs };
}

const box = document.querySelector(".box");
let startTime = null;

function frame(timestamp) {
  if (startTime === null) startTime = timestamp; // first frame
  const { progress, isComplete } = calculateAnimationProgress(startTime, timestamp, 1000);
  box.style.transform = `translateX(${progress * 240}px)`;
  if (!isComplete) requestAnimationFrame(frame);
}

requestAnimationFrame(frame);
Call elapsedMs progress isComplete
calculateAnimationProgress(0, 500, 1000) 500 0.5 false
calculateAnimationProgress(0, 1000, 1000) 1000 1 true
calculateAnimationProgress(0, 1500, 1000) 1500 1 true
calculateAnimationProgress(100, 100, 1000) 0 0 false

For motion with no duration, such as a ball in a game, use delta time: the difference between this frame's timestamp and the previous one. x += 240 * (delta / 1000) means 240 px per second, however many frames there are.

Stopping an animation

let id = requestAnimationFrame(frame); // every frame, keep the newest id
// inside frame: id = requestAnimationFrame(frame);

cancelAnimationFrame(id); // the scheduled frame is cancelled

requestAnimationFrame returns a number, the id. cancelAnimationFrame(id) cancels the callback that hasn't run yet, so the loop stops. You must call it when the element is removed from the page, for example when a component unmounts. Otherwise the loop keeps running, moving an element that no longer exists.

⚠️ Animations that overshoot or won't stop

TL;DR: requestAnimationFrame(fn) calls fn right before the next frame is drawn, following the screen: about 60 times a second at 60 Hz, more at 120 Hz, and it stops in a hidden tab. setInterval isn't in step with the screen. Work out motion from the timestamp: progress = Math.min((currentTime - startTime) / duration, 1), isComplete = progress >= 1, and elapsedMs left as it is. A fixed step per frame gets faster on a 120 Hz screen. Keep the newest id, then cancelAnimationFrame(id) to stop, including when the element is removed.

⚡ Draw right before the next frame

Write:

function frame() {
  x += 4;
  box.style.transform = `translateX(${x}px)`;
  if (x < 240) requestAnimationFrame(frame);
}
Guess first: why is requestAnimationFrame better than setInterval for animation?

rAF follows the screen's refresh rate: it's called right before a frame is drawn, and it stops in a hidden tab. setInterval runs on its own clock, no matter when the browser draws.

Meaning: rAF schedules frame once. To make an animation, frame schedules itself again.

⚡ Motion from time

Write:

const elapsedMs = currentTime - startTime;
const progress = Math.min(elapsedMs / duration, 1);
return { progress, isComplete: progress >= 1, elapsedMs };

Meaning: x += 4 is twice as fast on a 120 Hz screen. Work out the position from the time that has passed, so the animation ends at 1,000 ms on any screen. Math.min holds progress at 1, but elapsedMs stays as it is.

⚡ Stopping an animation

Meaning: requestAnimationFrame returns an id. Keep the newest id on every frame, then call cancelAnimationFrame(id) to stop, including when the element is removed from the page.

What you will learn