requestAnimationFrame()

tera8485537273's avatar
Published Feb 25, 2025
Contribute to Docs

The requestAnimationFrame() function schedules a function to run before the next repaint. It is used to create smooth animations.

Syntax

requestAnimationFrame(callback)
  • callback: The callback function to be executed before the next repaint.

Example

In the following example, the JavaScript will animate the red box, moving it from left to right within the container using requestAnimationFrame(). The animation will continue until the box reaches 300px:

// Selecting the box element
const box = document.getElementById('box');
let position = 0;
function animate() {
position += 2;
box.style.transform = `translateX(${position}px)`;
if (position < 300) {
requestAnimationFrame(animate);
}
}
// Starting the animation
requestAnimationFrame(animate);

Once the HTML and CSS have been added, the result will be as follows:

Browser Output of the above code

All contributors

Contribute to Docs

Learn JavaScript on Codecademy