Codectionary / Developer documentation / JavaScript

Animating with requestAnimationFrame

requestAnimationFrame schedules a one-shot callback before a future repaint. Use the supplied timestamp to calculate progress independently of display refresh rate. Frames may pause in background tabs, so frame counts are not a reliable clock.

Syntax

const id = requestAnimationFrame(timestamp => { /* draw */ });
cancelAnimationFrame(id);

Examples

Animating with requestAnimationFrame: working example

Run this standalone example in a modern browser console unless another environment is specified. Expected result: In a visible browser page, a blue square moves 120 pixels right over roughly one second and logs Finished.

const box = document.createElement("div");
box.style.cssText = "width:30px;height:30px;background:royalblue";
document.body.append(box);
let start;
function frame(time) {
  start ??= time;
  const progress = Math.min((time - start) / 1000, 1);
  box.style.transform = `translateX(${progress * 120}px)`;
  if (progress < 1) requestAnimationFrame(frame);
  else console.log("Finished");
}
requestAnimationFrame(frame);
  1. Expected result: In a visible browser page, a blue square moves 120 pixels right over roughly one second and logs Finished.
  2. Each callback requests the next frame only while work remains.
  3. Elapsed timestamps determine progress, so faster displays do not make the animation run faster.

Best practices

  • Cancel pending animation callbacks during component cleanup.
  • Respect reduced-motion preferences in production animation interfaces.

Runtime & versions

Browsers and JavaScript runtimes. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

ECMAScript specification

Specifications & further reading