RequestAnimationFrame in JavaScript

RequestAnimationFrame in JavaScript

ยท

2 min read

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.

Buy Me A Coffee

๐ŸŒŸ Twitter ๐Ÿ‘ฉ๐Ÿปโ€๐Ÿ’ป suprabha.me ๐ŸŒŸ Instagram

Did you find this article valuable?

Support Suprabha Supi by becoming a sponsor. Any amount is appreciated!