When to Use
- Animating DOM elements with JavaScript.
- Batching DOM reads and writes to prevent Layout Thrashing.
- Throttling high-frequency events (like scroll or mousemove).
When NOT to Use
- For simple animations where CSS transitions or @keyframes are sufficient.
- Executing heavy computational logic that blocks the main thread.
- For asynchronous tasks that do not involve visual updates (use setTimeout or Web Workers instead).
Code Examples
Fixing Layout Thrashing
By deferring the style mutation to the next frame, the browser avoids recalculating the layout synchronously, preserving a smooth 60fps.
// Bad: Causes synchronous layout
const w = box.offsetWidth;
box.style.width = w + 10 + 'px';
// Good: Read now, write in next frame
const w = box.offsetWidth;
requestAnimationFrame(() => {
box.style.width = w + 10 + 'px';
});