← Lessons

quiz vs the machine

Gold1380

Frontend

The requestAnimationFrame Loop

Scheduling work in sync with the display's refresh.

5 min read · core · beat Gold to climb

What it solves

Animating with setInterval guesses at timing and drifts out of sync with the screen. requestAnimationFrame, often shortened to rAF, schedules a callback to run just before the next repaint.

How it behaves

  • Callbacks fire at the display refresh rate, commonly 60 times per second.
  • The callback receives a high resolution timestamp you use to compute progress.
  • When a tab is in the background, the browser pauses rAF, saving battery.

Writing a loop

A smooth animation reschedules itself: each callback does a small update and then calls rAF again for the following frame. Because all callbacks for a frame run together right before paint, your visual changes land in a single coherent frame.

Frame budget

At 60 frames per second you have about 16 milliseconds per frame for everything: your JavaScript, style, layout, paint, and composite. Overrunning that budget drops frames and looks janky.

Good practice

  • Drive position from the timestamp, not a fixed increment, so motion is frame rate independent.
  • Keep per frame work small and avoid forced reflows inside the callback.

Key idea

requestAnimationFrame runs your callback right before each repaint at the refresh rate, giving roughly a sixteen millisecond budget per frame.

Check yourself

Answer to earn rating on the learn ladder.

1. When does a requestAnimationFrame callback run?

2. Roughly how much time do you have per frame at 60 fps?

3. Why drive animation from the timestamp instead of a fixed step?