DEV Community

Cover image for RequestAnimationFrame in JavaScript

Posted on

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.


Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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() {
console.log("reqAnimationId", reqAnimationId)
Enter fullscreen mode Exit fullscreen mode

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 👩🏻‍💻 🌟 Instagram

Top comments (1)

jonrandy profile image
Jon Randy 🎖️

The problem with the example is that it doesn't really animate anything - making it difficult if not impossible to see the effect of requestAnimationFrame