requestAnimationFrame for Visual Updates
You'll learn when to use requestAnimationFrame instead of setTimeout for work that affects what users see on screen.
The Core Difference
You've learned that setTimeout helps you break up long tasks and yield control back to the browser. But when your JavaScript needs to make visual changes—like animating elements, updating positions, or manipulating the DOM in ways that affect rendering—there's a better tool: requestAnimationFrame.
Why Timing Matters for Visual Updates
Think of setTimeout as scheduling work for "sometime soon," but requestAnimationFrame is like saying "right before the next frame paints." Browsers repaint the screen roughly 60 times per second (every ~16ms). If you schedule visual updates with setTimeout, they might run at awkward times—halfway between frames, or multiple times before a single frame, wasting CPU cycles on changes users never see.
requestAnimationFrame synchronizes your code with the browser's rendering pipeline. It runs your callback right before the browser repaints, ensuring your visual changes are efficient and smooth.
When to Choose Each
Use requestAnimationFrame for:
- Animations and transitions
- Scroll position updates
- Canvas drawing operations
- Any DOM manipulation tied to visual display
Use setTimeout for:
- Breaking up non-visual computation
- Scheduling work that doesn't need rendering sync
- Delayed actions unrelated to animation
The Analogy
Imagine painting a room. setTimeout is like dabbing paint whenever you feel like it—sometimes twice before the wall dries, sometimes after people have already looked at it. requestAnimationFrame is like having someone tell you "now!" right before each inspection, so your work is always fresh and visible.
Key Takeaway: Use requestAnimationFrame instead of setTimeout when your JavaScript updates the visual display—it synchronizes with the browser's repaint cycle for smooth, efficient rendering.