requestAnimationFrame for Smooth Timing
You'll learn: How to synchronize your animations with the browser's refresh rate for buttery-smooth motion instead of using timer-based approaches.
The Problem with setTimeout and setInterval
When you use setTimeout or setInterval for animations, you're essentially guessing when the browser will paint the next frame. The browser repaints at ~60fps (every 16.67ms), but your timer might fire at 15ms or 18ms—out of sync with the actual refresh. This creates stuttering, wasted CPU cycles, and janky animations.
Think of it like trying to jump rope when someone else is turning it. If you jump on your own schedule instead of watching the rope, you'll trip.
Enter requestAnimationFrame
requestAnimationFrame (rAF) tells the browser: "Call my function right before the next repaint." The browser handles the timing, ensuring your animation code runs exactly when it can be displayed.
function animate() {
// Your animation logic here
element.style.transform = `translateX(${x}px)`;
x += 2;
// Schedule next frame
requestAnimationFrame(animate);
}
// Start the animation loop
requestAnimationFrame(animate);
Why It's Superior
- Perfectly synced with monitor refresh (60Hz, 120Hz, etc.)
- Automatic pausing when tab is inactive (saves battery!)
- No frame skipping or duplicate frames
- Better performance through browser optimization
You can cancel it too:
const animationId = requestAnimationFrame(animate);
cancelAnimationFrame(animationId); // Stop it
Key Takeaway: Always use requestAnimationFrame instead of setTimeout for animations—it synchronizes with the browser's refresh cycle, preventing jank and improving performance automatically.