# requestAnimationFrame()

> The `requestAnimationFrame()` JS browser API method schedules a function to be called before the next repaint, typically used for animations.

## How do I use requestAnimationFrame() for smooth animations?

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.

- Topic: Scheduling Tasks
- Type: method
- Browser support: Chrome 24+, Chrome Android 25+, Edge 12+, Firefox 23+, Firefox Android 23+, Safari 7+, Safari iOS 7+

## Example

Wrong:

```js
function step() {
  x += 2;
  box.style.transform = `translateX(${x}px)`;
  requestAnimationFrame(step);
}
requestAnimationFrame(step);
```

Right:

```js
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.

## Related cards

- [setInterval()](https://wonderium.dev/js/set-interval.md)
- [animation](https://wonderium.dev/css/animation.md)
- [transition](https://wonderium.dev/css/transition.md)
- [Repaint](https://wonderium.dev/web/repaint.md)
- [Event Loop](https://wonderium.dev/js/event-loop.md)

---

- Level: [JavaScript](https://wonderium.dev/js.md)
- HTML version: https://wonderium.dev/js/request-animation-frame
- Last updated: 2026-11-25
