0
0
JavascriptConceptBeginner · 3 min read

What is requestAnimationFrame in JavaScript: Explanation and Example

requestAnimationFrame is a JavaScript function that tells the browser to run a specified animation function before the next screen repaint. It helps create smooth animations by syncing updates with the browser's refresh rate, making animations efficient and less CPU-intensive.
⚙️

How It Works

Imagine you want to draw a moving ball on a screen. Instead of drawing it as fast as possible, requestAnimationFrame asks the browser, "Hey, can you call this function right before you refresh the screen?" This way, the animation updates happen exactly when the screen is ready to show new content.

This syncing prevents wasted work and makes animations smoother because the browser controls the timing. It’s like a dance where the browser leads, and your animation follows the beat of the screen refresh.

💻

Example

This example moves a square smoothly across the screen using requestAnimationFrame. The function updates the square's position and asks the browser to call it again before the next repaint.

javascript
const box = document.createElement('div');
box.style.width = '50px';
box.style.height = '50px';
box.style.backgroundColor = 'blue';
box.style.position = 'absolute';
box.style.left = '0px';
document.body.appendChild(box);

let position = 0;

function animate() {
  position += 2; // move 2 pixels
  box.style.left = position + 'px';
  if (position < window.innerWidth - 50) {
    requestAnimationFrame(animate);
  }
}

requestAnimationFrame(animate);
Output
A blue square moves smoothly from left to right across the screen until it reaches the edge.
🎯

When to Use

Use requestAnimationFrame when you want to create smooth animations or visual updates in the browser. It is perfect for moving objects, fading effects, or any changes that happen over time.

It is better than using timers like setTimeout or setInterval because it pauses animations when the user switches tabs, saving battery and CPU. This makes it ideal for games, interactive graphics, or dynamic user interfaces.

Key Points

  • Syncs animation with browser refresh for smooth visuals.
  • Improves performance by pausing when not visible.
  • Replaces timers for better animation control.
  • Easy to use with a simple callback function.

Key Takeaways

requestAnimationFrame schedules animation updates just before the browser repaints the screen.
It creates smoother animations by syncing with the display refresh rate.
It saves resources by pausing animations when the page is not visible.
Use it instead of timers for better animation performance and control.