← Lessons

quiz vs the machine

Silver1100

Frontend

requestAnimationFrame

Schedule visual updates in sync with the browser's repaint.

4 min read · intro · beat Silver to climb

The timing problem

Animating with setInterval picks an arbitrary rate that drifts out of step with the screen. Updates can land between paints, wasting work or causing stutter.

The solution

requestAnimationFrame asks the browser to run your callback right before the next repaint. It naturally matches the display refresh, typically sixty times a second, so motion looks smooth.

How to animate

  • You call it with a callback that updates positions.
  • The callback receives a timestamp for computing how far to move.
  • To keep animating, the callback schedules itself again.

Why it is better

The browser pauses callbacks when the tab is hidden, saving battery and CPU. Updates are batched into the paint cycle, avoiding the tearing and jank of timer based loops.

Key idea

requestAnimationFrame runs your visual updates in sync with the browser repaint for smooth, efficient animations that pause when the tab is hidden.

Check yourself

Answer to earn rating on the learn ladder.

1. When does requestAnimationFrame run your callback?

2. What happens to scheduled frames when the tab is hidden?