What You'll Learn
You'll learn how to synchronize JavaScript-driven animations with the browser's natural refresh cycle for buttery-smooth visual updates.
The Problem with Regular Timing Functions
When you use setTimeout() or setInterval() to animate elements with JavaScript, you're essentially guessing when the browser will next paint to the screen. Browsers typically refresh at 60 frames per second (every ~16.67ms), but your timer might fire at awkward moments—like right after a frame has painted. This mismatch causes jank, stuttering, and wasted CPU cycles.
How requestAnimationFrame Works
requestAnimationFrame() tells the browser: "Hey, I want to update something visual—call my function right before your next repaint." The browser then schedules your code to run at the optimal moment, perfectly synchronized with its rendering pipeline.
Think of it like this: If setTimeout is like showing up randomly to catch a bus, requestAnimationFrame is like checking the bus schedule and arriving exactly when it pulls up.
Basic Usage
function animate() {
// Update element positions, styles, etc.
element.style.transform = `translateX(${position}px)`;
// Request the next frame
requestAnimationFrame(animate);
}
// Start the animation loop
requestAnimationFrame(animate);
The browser automatically pauses requestAnimationFrame when the tab isn't visible, saving battery life—something setInterval doesn't do.
Why This Matters for Performance
Since you've learned about composite-only animations and hardware acceleration, requestAnimationFrame is the JavaScript companion that ensures your transform and opacity changes happen at exactly the right moment in the rendering pipeline. No reflow, no wasted frames—just smooth 60fps motion.
Key Takeaway: Always use requestAnimationFrame() instead of timers for JavaScript animations—it syncs perfectly with the browser's refresh cycle, prevents jank, and automatically pauses when tabs are hidden.