requestAnimationFrame vs setTimeout
What you'll learn: Why requestAnimationFrame is the secret weapon for silky-smooth 60fps animations while setTimeout can create janky results.
The Core Difference
Both requestAnimationFrame and setTimeout schedule code to run later, but they synchronize with different clocks. setTimeout runs after a specified delay regardless of what the browser is doing. requestAnimationFrame runs right before the browser repaints the screen—perfectly timed for visual updates.
Think of it like this: setTimeout is like setting an alarm clock that rings at fixed intervals, even if you're in the middle of something. requestAnimationFrame is like a personal assistant who taps you on the shoulder only when you're ready to take action.
Why Sync Matters
Browsers repaint the screen approximately 60 times per second (16.67ms between frames). If you use setTimeout with a 16ms delay, your updates might arrive between repaints—wasted work the user never sees, or worse, updates that arrive slightly out of sync, causing stutter.
requestAnimationFrame guarantees your animation code runs exactly once per repaint cycle. No wasted calculations. No janky timing. The browser may even throttle it when the tab is hidden, saving battery life.
When to Use Each
Use requestAnimationFrame when animating visual properties (position, scale, color). Use setTimeout for time-based logic that doesn't need visual precision (debouncing, polling, delayed actions).
In React, you'll typically call requestAnimationFrame inside useEffect for manual animations, though modern animation libraries handle this internally.
Key Takeaway: requestAnimationFrame syncs with the browser's repaint cycle for smooth 60fps animations, while setTimeout runs on its own schedule and can cause janky, inefficient visual updates.