requestAnimationFrame()
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 elementconst box = document.getElementById('box');let position = 0;function animate() {position += 2;box.style.transform = `translateX(${position}px)`;if (position < 300) {requestAnimationFrame(animate);}}// Starting the animationrequestAnimationFrame(animate);
Once the HTML and CSS have been added, the result will be as follows:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn JavaScript on Codecademy
- Career path
Front-End Engineer
Front-end engineers work closely with designers to make websites beautiful, functional, and fast.Includes 34 CoursesWith Professional CertificationBeginner Friendly115 hours - Free course
Learn JavaScript
Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.Beginner Friendly15 hours