requestAnimationFrame & Smooth Animations
requestAnimationFrame & Smooth Animations in Modern JavaScript
Creating fluid visual animations in web applications requires synchronizing JavaScript execution with the display hardware's vertical synchronization (V-Sync). Using setInterval or setTimeout for animations causes frame drops, stuttering, and wasted CPU cycles. requestAnimationFrame() is the browser's native API for high-performance visual animations.
1. Why setTimeout & setInterval Fail at Animations
Most computer and mobile displays refresh at 60Hz (once every 16.67ms) or 120Hz (once every 8.33ms).
Flaws of Timer-Based Animations:
- 1Misaligned with Hardware V-Sync: Timers fire independently of screen refresh cycles.
- 2Continues in Background Tabs:
setIntervalkeeps running even when the user switches tabs, draining laptop battery and mobile CPU! - 3Timer Throttling: Browsers throttle
setTimeoutto 1,000ms in inactive tabs.
2. The requestAnimationFrame Mechanics
window.requestAnimationFrame(callback):
- 1Fires immediately before the browser's next screen repaint, perfectly in sync with V-Sync.
- 2Automatically pauses when the browser tab is minimized or inactive, conserving battery.
- 3Automatically passes a high-resolution DOMHighResTimeStamp (
performance.now()) to the callback.
3. Canceling Animations: cancelAnimationFrame()
To stop an in-flight animation loop (e.g. on user click, modal close, or component unmount):
4. Physics Animation Loop Pattern (Delta Time)
To ensure game physics and animations run at the exact same speed on 60Hz, 120Hz, and 144Hz monitors, always calculate Delta Time ($\Delta t$):
Practice Quiz
Memory Management & Garbage Collection
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Critical Rendering Path & Reflow/Repaint | Memory Management & Garbage Collection |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.