requestAnimationFrame() All you need to know

Everything about window.requestAnimationFrame() and how to use it.

·

2 min read

So, you want to make some animations with JS. Handling JavaScript animations with setTimeout or setInterval would lead to junky movements of elements. And in this case, requestAnimationFrame is here to help.

window.requestAnimationFrame() will be called every time the browser is going to repaint. You can pass your callback inside of requestAnimationFrame and this callback should call requestAnimationFrame itself if you want to continue the animation.

requestAnimationFrame(() => { 
  ...
  requestAnimationFrame(() => {...})
})

By default browser will try to call requestAnimationFrame 60 times per second, but the amount of calls depends on the device and its refresh rates. So, to make the experience consistent on all devices, you will need to keep track of the amount of time this animation is running you can do it like this

let start; 
function animation(timeStamp) {
  if (start === undefined) {
    start = timeStamp
  }
  const elapsed = timeStamp - start

  // do some animation

  if (elapsed < 3000) {
    window.requestAnimationFrame(animation)
  }
}

window.requestAnimationFrame(animation)

Here we create a variable where we will store the beginning of our animation, callback for requestAnimationFrame and call it for the first time. In the callback, we check if we already saved the start of the animation, if not -> save it. Then we calculate how long the animation is lasting, do some animations and check if the animation lasts for less than 3 seconds, then we continue the animation.

So, with the help of requestAnimationFrame you can easily create JS-based animations for any element and guarantee a smooth user experience.