requestAnimationFrame()

Term side of the Card.
Topic: Scheduling Tasks
Unit title: requestAnimationFrame()
Categories: Method
Explanation side of the Card

Explanation: The browser API method that schedules a function to be called before the next repaint, ensuring smooth animations by syncing with the browser's refresh rate. It's commonly used to update the position of elements in animations or games.

Browser compatibility:
  • The chrome browser supports this feature starting from version 24.
  • The edge browser supports this feature starting from version 12.
  • The firefox browser supports this feature starting from version 23.
  • The safari browser supports this feature starting from version 7.
Availability: 

Example

Wrongjs
function step() {
  x += 2;
  box.style.transform = `translateX(${x}px)`;
  requestAnimationFrame(step);
}
requestAnimationFrame(step);
Rightjs
let start;
function step(time) {
  start ??= time;
  const x = Math.min((time - start) * 0.1, 300);
  box.style.transform = `translateX(${x}px)`;
  if (x < 300) requestAnimationFrame(step);
}
requestAnimationFrame(step);

Position depends on elapsed time, so speed is the same at any refresh rate, and the loop ends at the target.

Common mistakes

  • Moving an element a fixed number of pixels per frame, so it runs faster on 120 Hz screens.
  • Expecting callbacks to keep running in a background tab, where browsers pause them.

Key points

  • Movement uses the callback's timestamp to compute elapsed time, not a fixed step per frame.
  • The ID is stored and the loop is stopped with cancelAnimationFrame() or an end condition.
  • Simple effects use CSS transition or animation instead of a JS loop.
  • The animation respects prefers-reduced-motion.

Interview questions

requestAnimationFrame vs setInterval: which is better for animation?

requestAnimationFrame(). It runs in step with the screen refresh and pauses in hidden tabs, while setInterval() can drop or double frames.

How often does requestAnimationFrame() run?

Usually once per screen refresh: about 60 times per second on a 60 Hz display, and more often on faster screens.

Analytics cookiesWe'd like to use analytics cookies to see which pages are useful. They're set only if you accept. Privacy Policy