Skip to main content

Using requestAnimationFrame for Smooth Animations (Live Playground)

The requestAnimationFrame function is a browser API that allows you to create smooth and efficient animations by calling a specified function before the browser performs the next repaint. This ensures that your animations are in sync with the browser's refresh rate, leading to smoother animations and better performance.

Why use requestAnimationFrame?

Using requestAnimationFrame has several benefits:

  1. Optimized frame rate: The browser adjusts the frame rate based on the device's performance, ensuring a consistent experience across different devices.
  2. Reduced CPU usage: The function is not called when the tab is inactive or minimized, which helps reduce CPU usage and saves battery life on mobile devices.
  3. Better synchronization: Animations are synchronized with the browser's refresh rate, reducing jank and providing smoother animations.

How to use requestAnimationFrame

To use requestAnimationFrame, you need to pass a callback function as an argument. The callback function will be executed before the next repaint, and it typically contains the code for updating your animation.

Here's a simple example of using requestAnimationFrame to create a smooth animation:

<!DOCTYPE html>
.box {
width: 50px;
height: 50px;
background-color: red;
position: absolute;
let posX = 0;
const speed = 2;

function animate() {
// Update the position of the box
posX += speed;

// Apply the new position to the box
const box = document.querySelector('.box'); = `translateX(${posX}px)`;

// Request the next frame

window.addEventListener('DOMContentLoaded', () => {
// Start the animation
<div class="box"></div>

In this example, we use requestAnimationFrame to move a box smoothly across the screen. The animate function is called repeatedly, updating the position of the box and requesting the next frame.

By using requestAnimationFrame, you can create smooth and efficient animations that are optimized for performance and provide a better user experience.

Live Playground, Try it Yourself