🟨 JavaScript Q79 / 121

Explain requestAnimationFrame.

AI-Powered Answer ✓ Answered

requestAnimationFrame is a JavaScript API designed for performing animations and visual updates in the browser in an optimized and efficient manner. It provides a way to tell the browser that you want to perform an animation and requests the browser to call a specified function to update an animation before the browser's next repaint.

What is requestAnimationFrame?

Unlike traditional methods like setTimeout or setInterval, requestAnimationFrame is specifically tailored for high-performance animations. It allows the browser to optimize concurrent animations into a single reflow and repaint cycle, leading to smoother animations and more efficient resource usage. The browser controls when the callback function is executed, typically just before the browser performs its next screen repaint, ensuring synchronization with the display's refresh rate.

How it Works

When you call requestAnimationFrame and pass it a callback function, you're essentially asking the browser to execute that function just before the next screen refresh. The browser then decides the optimal time to do this. The callback function receives a single argument: a DOMHighResTimeStamp, which indicates the time when requestAnimationFrame started to fire callbacks for the current frame. To create continuous animations, the callback function must recursively call requestAnimationFrame again.

Advantages of requestAnimationFrame

  • Efficiency & Performance: It allows the browser to optimize animations by synchronizing them, reducing CPU and GPU usage.
  • Synchronization with Browser: The browser ensures the animation updates are processed before a repaint, preventing visual tearing and ensuring smooth playback.
  • Battery Life Optimization: When a tab with requestAnimationFrame is in the background or hidden, the browser pauses the animation to save battery life and system resources.
  • Less Janky Animations: By coordinating with the browser's refresh rate, it helps deliver animations at a consistent frame rate, avoiding dropped frames and creating a smoother experience.
  • Timestamp for Precise Timing: The callback receives a high-resolution timestamp, enabling more accurate timing of animation steps compared to Date.now().

Basic Usage Example

javascript
const element = document.getElementById('my-animated-element');
let start = null;

function step(timestamp) {
  if (!start) start = timestamp;
  const progress = timestamp - start;
  // Move element 100 pixels over 2 seconds (2000ms)
  element.style.transform = `translateX(${Math.min(progress / 20, 100)}px)`;

  if (progress < 2000) { // Continue for 2 seconds
    window.requestAnimationFrame(step);
  }
}

window.requestAnimationFrame(step);

Key Considerations

  • It is not suitable for operations that need to run at a precise, fixed interval (e.g., a stopwatch counting seconds) if the tab is inactive.
  • The callback needs to recursively call requestAnimationFrame to continue the animation loop.
  • The frame rate provided by requestAnimationFrame can vary depending on the browser's refresh rate, system load, and whether the tab is active.

In summary, requestAnimationFrame is the preferred method for building any kind of visual animation or interactive display update in modern web development due to its efficiency, synchronization with the browser, and ability to optimize resource usage.