RequestAnimationFrame in JavaScript

Using the native requestAnimationFrame method we can make our browser repeat something very quickly forever. It calls itself to paint the next frame.

📝 Note: Your callback routine must itself call requestAnimationFrame() again if you want to animate another frame at the next repaint. requestAnimationFrame() is 1 shot.

requestAnimationFrame takes one argument, only callback.

Syntax:
window.requestAnimationFrame(callback);

callback: The function to call 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 same time.

The goal is 60 frame per second(fps) to appear smooth animation.

So we do like this 👇

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

But now we have requestAnimationFrame, which is more better and optimized:

  • Animations will be so smooth as its optimized
  • Animations in inactive tabs will stop, allowing the CPU to chill

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

function smoothAnimation() {
// animtion
requestAnimationFrame(smoothAnimation)
}
requestAnimationFrame(smoothAnimation)

How can you start and stop animation ⏲️

requestAnimationFrame 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)

Checkout the codepen here for more details:

Reference 🧐

Summary ∑

If you do any animation on browser and wanted it to be optimised, then would highly recommend to use requestAnimationFrame web API.

Thanks for reading the article ❤️

I hope you love the article. If you have any question, feel free to ping me on Twitter | Instagram 😋