Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท Promises and Async

The requestAnimationFrame() function

Reference for requestAnimationFrame(): scheduling animation work before the next repaint, using the timestamp, cancelling frames, and avoiding common pitfalls.

requestAnimationFrame() asks the browser to call your function just before it paints the next frame. It is the right tool for animations and for any visual update that should stay in step with the display: the browser runs your callback once per screen refresh (typically 60 times a second, or more on faster displays) and pauses it entirely when the tab is hidden.

The callback runs once. To animate, call requestAnimationFrame() again from inside the callback.

JavaScript
function step(timestamp) {
  // update the page, then ask for another frame
  requestAnimationFrame(step);
}
requestAnimationFrame(step);

Try it

Time-based animation
JS Frames are asynchronous

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
const id = requestAnimationFrame(callback);
cancelAnimationFrame(id);
Name Description
callback Called with one argument: a high-resolution timestamp in milliseconds (the same time base as performance.now()), identical for every callback in the same frame.

Return value: a positive integer id for cancelAnimationFrame().

Usage notes

  • Use the timestamp, not a frame count. Displays refresh at different rates (60, 120, 144 Hz). Compute positions from elapsed time, as the first example does, so speed is the same everywhere.
  • Schedule the next frame from inside the callback to keep animating; stop by not scheduling, or by calling cancelAnimationFrame(id).
  • Hidden tabs pause. No frames run while the page is not visible, which saves battery. Do not use it for work that must continue, such as timers or network polling.
  • Batch reads and writes. Read layout values (like clientWidth) first and write styles after, to avoid forcing repeated layout.
  • Keep callbacks short. A slow callback drops frames. Move heavy computation elsewhere (a Web Worker, or chunks via requestIdleCallback()).
  • Prefer CSS transitions or animations for simple effects; use requestAnimationFrame() when JavaScript has to compute each frame (canvas, games, scroll-linked effects).
  • Not in Node.js and not available in most non-browser environments.
  • Respect user settings. Check matchMedia("(prefers-reduced-motion: reduce)") before running decorative animations.

Browser support

requestAnimationFrame() and cancelAnimationFrame() are supported by all current browsers.