Using the native requestAnimationFrame method in JavaScript, we can make our browser call and repeat an animation function very quickly forever. It calls itself to paint the next frame.

What Is requestAnimationFrame?

RequestAnimationFrame is an animation method in JavaScript that tells the browser to call a specific function and update the animation for the next repaint. It reduces the animation load on a CPU and allows the animations to run more smoothly. 

Your callback routine must itself call requestAnimationFrame() again if you want to animate another frame at the next repaint. requestAnimationFrame() is one shot. It takes one argument, the callback. Here’s what you need to know.

 

RequestAnimationFrame Syntax

window.requestAnimationFrame(callback);

callback is the function called when it’s time to update your animation for the next repaint.

Animations with requestAnimationFrame are non-blocking, which means if you make subsequent calls to requestAnimationFrame, the resulting animations will all occur at the same time.

More on JavaScript: 8 Common JavaScript Data Structures

 

Advantages of requestAnimationFrame

The goal is for smooth animation to appear at 60 frames per second (fps).

We could write our animation code like this:

setInterval(() => {
  // animation code
}, 1000/60);

But using requestAnimationFrame is more effective for two reasons:

  • Its animations are smoother because the function is optimized.
  • Animations in the inactive tabs will stop running, which allows the CPU to chill.

Let’s see how can we create the above snippet using requestAnimationFrame:

function smoothAnimation() {
    // animtion
    requestAnimationFrame(smoothAnimation)
}
requestAnimationFrame(smoothAnimation)
A tutorial on requestAnimationFrame in JavaScript. | Video: freeCodeCamp.org

More on JavaScript: What Are JavaScript Algorithms and Data Structures?

 

How to Use requestAnimationFrame

requestAnimationFrame also returns an ID you can use to cancel it.

let reqAnimationId;
function smoothAnimation() {
    // animtion
    reqAnimationId = requestAnimationFrame(smoothAnimation)
}
// to start
function start() {
    reqAnimationId = requestAnimationFrame(smoothAnimation)
}
// to end
function end() {
     cancelAnimationFrame(reqAnimationId)
}
console.log("reqAnimationId", reqAnimationId)

Check out the demo to see it in action.

Code animation results

If you do any animation on a browser and want it to be optimized, then I would highly recommend using the requestAnimationFrame web API.

Expert Contributors

Built In’s expert contributor network publishes thoughtful, solutions-oriented stories written by innovative tech professionals. It is the tech industry’s definitive destination for sharing compelling, first-person accounts of problem-solving on the road to innovation.

Learn More

Great Companies Need Great People. That's Where We Come In.

Recruit With Us