#atom
requestAnimationFrame - Efficient DOM Updates for Animations and UI
Core Idea:
requestAnimationFrame is a browser API that schedules a function to execute before the next repaint, providing a more efficient and smoother way to perform animations and DOM manipulations than traditional timing mechanisms.
Key Principles:
- Browser Optimization:
- Aligns code execution with the browser's natural render cycle.
- Throttling:
- Automatically pauses in inactive tabs or hidden iframes.
- Performance Alignment:
- Batches visual updates to prevent tearing and optimize rendering.
Why It Matters:
- Animation Smoothness:
- Produces more consistent frame rates and smoother animations.
- Battery Efficiency:
- Reduces power consumption by aligning with display refresh.
- Resource Management:
- Automatically throttles in background tabs to conserve resources.
How to Implement:
- Schedule Animation Frame:
const frameId = requestAnimationFrame(callback);
- Create Animation Loop:
- Recursively call within the callback for continuous animation.
- Cancel When Done:
cancelAnimationFrame(frameId);
when animation should stop.
Example:
-
Scenario:
- Creating a smooth scrolling animation to a specific element.
-
Application:
function smoothScrollTo(element) {
const start = window.pageYOffset;
const target = element.getBoundingClientRect().top + start;
const duration = 500; // ms
let startTime = null;
function animate(currentTime) {
if (!startTime) startTime = currentTime;
const timeElapsed = currentTime - startTime;
const progress = Math.min(timeElapsed / duration, 1);
const easeProgress = 0.5 - Math.cos(progress * Math.PI) / 2;
window.scrollTo(0, start + (target - start) * easeProgress);
if (timeElapsed < duration) {
requestAnimationFrame(animate);
}
}
requestAnimationFrame(animate);
}
```
- Result:
- Smooth scrolling animation that's synchronized with the browser's refresh rate.
Connections:
- Related React Concepts:
- useEffect: Often used to manage rAF initialization and cleanup.
- useRef: Used to store animation frame IDs for cancellation.
- Broader Programming Concepts:
- Render Loop: Game/animation programming pattern.
- Debouncing/Throttling: Controlling execution frequency.
References:
- Primary Source:
- MDN Web Docs, Window.requestAnimationFrame()
- Additional Resources:
Tags:
#JavaScript #Animation #Performance #DOM #requestAnimationFrame #Rendering
Connections:
Sources:
- From: AG Grid