#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:

  1. Browser Optimization:
    • Aligns code execution with the browser's natural render cycle.
  2. Throttling:
    • Automatically pauses in inactive tabs or hidden iframes.
  3. Performance Alignment:
    • Batches visual updates to prevent tearing and optimize rendering.

Why It Matters:


How to Implement:

  1. Schedule Animation Frame:
    • const frameId = requestAnimationFrame(callback);
  2. Create Animation Loop:
    • Recursively call within the callback for continuous animation.
  3. Cancel When Done:
    • cancelAnimationFrame(frameId); when animation should stop.

Example:

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);
}
```


Connections:


References:

  1. Primary Source:
    • MDN Web Docs, Window.requestAnimationFrame()
  2. Additional Resources:

Tags:

#JavaScript #Animation #Performance #DOM #requestAnimationFrame #Rendering


Connections:


Sources: