Understanding requestAnimationFrame

Understanding requestAnimationFrame

We have been using setInterval to manage all JavaScript animations.

setInterval (performAnimation, 100);

Here 100 is quite a tricky magical number. It is very difficult to come with this number (delay). It needs to be short enough so that the animations are smooth but long enough to produce changes which browser can render.

An interesting fact to consider here is most monitors refresh screen at the rate of 60Hz i.e. 60 times per second which means 60 FPS (frames per second). Thus, the best interval for animation turns out to be 17ms (1000ms/60).

To create a smooth animation one needs to exactly know when the next frame will be drawn. CSS animations/transitions are smooth because the browser knows that an animation is about to happen and then can refresh the UI accordingly. But in case of JavaScript the browser has no idea that an animation is about to happen.

requestAnimationFrame is a way to tell browser that some JavaScript animation is taking place.

requestAnimationFrame takes a function (callback) as an only argument which-

  • is executed before repainting the screen.

  • needs to make all the required changes to the DOM that are to be reflected as part of the next repaint.

  • is invoked only once.

  • receives an argument that is a time code — [**DOMHighResTimeStamp](https://developer.mozilla.org/en-US/docs/Web/API/DOMHighResTimeStamp).**

Now, to perform an animation this callback function has to be called multiple times.

function performAnimation () {
  //Actual animation implementation
  if(!isAnimationComplete) {
    requestAnimationFrame(performAnimation);
  }
}
requestAnimationFrame(performAnimation);

Go ahead and make your animations smoother using requestAnimationFrame.

Best luck requesting an animation frame the next time you animate something…

Did you find this article valuable?

Support Niranjan Borawake by becoming a sponsor. Any amount is appreciated!