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.