Back to APIs

requestAnimationFrame

Rendering

A method that tells the browser you wish to perform an animation and requests that the browser calls a specified function to update an animation before the next repaint.

SupportGlobal 98%+
BaselineWidely available
ImpactHigh
Popularity🔥 95

When to Use

  • Animating DOM elements with JavaScript.
  • Batching DOM reads and writes to prevent Layout Thrashing.
  • Throttling high-frequency events (like scroll or mousemove).

When NOT to Use

  • For simple animations where CSS transitions or @keyframes are sufficient.
  • Executing heavy computational logic that blocks the main thread.
  • For asynchronous tasks that do not involve visual updates (use setTimeout or Web Workers instead).

Code Examples

Fixing Layout Thrashing

By deferring the style mutation to the next frame, the browser avoids recalculating the layout synchronously, preserving a smooth 60fps.

// Bad: Causes synchronous layout
const w = box.offsetWidth;
box.style.width = w + 10 + 'px';

// Good: Read now, write in next frame
const w = box.offsetWidth;
requestAnimationFrame(() => {
  box.style.width = w + 10 + 'px';
});

Advantages

  • Synchronizes automatically with the display refresh rate (usually 60fps).
  • Pauses automatically when the user switches tabs, saving battery and CPU.
  • Groups multiple DOM manipulations into a single repaint.

Limitations

  • Executes strictly on the Main Thread. If the thread is blocked, rAF will be delayed (jank).
  • Not suitable for exact millisecond-precise timing (unlike Web Audio API).

Common Mistakes

  • Reading layout properties (offsetWidth) immediately after writing to them inside the same rAF callback.
  • Failing to cancel the animation frame using cancelAnimationFrame when the component unmounts.
  • Doing heavy JSON parsing or array mapping inside the rAF callback, causing frame drops.

References