Concept Explanation
Your monitor repaints about 60 times per second — once every ~16 milliseconds. If you animate with setInterval, your code and the screen's refresh drift out of sync, causing stutter (we call it "jank").
requestAnimationFrame (rAF) is like handing your drawing to a painter who only paints on the beat. You say "run this right before the next repaint," and the browser schedules it perfectly in time with the screen — and pauses it entirely when the tab is hidden, saving battery.
Syntax or Core Structure
function step(timestamp) {
box.style.transform = "translateX(" + (timestamp / 10) + "px)";
requestAnimationFrame(step); // schedule the next frame
}
requestAnimationFrame(step); // start the loop
The browser passes a timestamp to your function, so you can animate based on time rather than frame count — smooth even if a frame gets dropped.
Real World Example
Games & smooth scrolling: Every browser game, physics simulation, and smooth-scroll library runs on rAF. It is the heartbeat of the render loop.
Common Mistakes
- setInterval for animation: It ignores the refresh rate and keeps running on hidden tabs, wasting CPU.
- Heavy Work Inside: A frame budget is only ~16ms. Do expensive math in a Web Worker, not in the rAF callback.
- Never Cancelling: Store the id (
const id = requestAnimationFrame(...)) and callcancelAnimationFrame(id)to stop a loop.
Best Practices
- Animate Transforms: Change
transformandopacity(cheap for the GPU) rather thantop/left(which force a slow layout). - Use the Timestamp: Base movement on elapsed time so animations run the same speed on every device.
Practice Exercises
- The Slider: Move a box across the screen smoothly using rAF and the timestamp.
- The Stopwatch: Build a millisecond timer that updates on every frame.
- The Pause Test: Log a message each frame, switch tabs, and watch how rAF pauses automatically.