Animating with requestAnimationFrame

widget

When you are creating an animation, it goes without saying that you want your animation to run smoothly and fluidly when someone is viewing it. If you are using CSS Animations, then you have nothing to worry about. Your browser takes care of everything for you. If you are creating your animation using JavaScript, things are a bit different. Instead of the browser giving you some assistance, you are left on your own. It is up to you to make sure your animation runs smoothly while at the same time taking into account the various factors that could affect your animation’s performance. Factors such as other things happening on the page. Factors such as your laptop / phone / tablet going into battery mode and halving its performance reduced. Factors such as another tab taking focus. You get the point.

Times have changed. Your prayers have been answered. You now have help in the form of the requestAnimationFrame function that allows you to create smooth and fluid animations in JavaScript without…you actually having to worry about making it smooth and fluid. Just add a few calls to requestAnimationFrame and your browser takes care of the rest. That’s it.

In case you are still skeptical whether this function will do what I claim, below is an example of a JavaScript-based animation that I created using requestAnimationFrame:

I’m not using functions like setInterval or setTimeOut to create my animation loop or anything like that. It’s all taken care of by requestAnimationFrame, and in this tutorial, you will learn all about this magical function and how you can use it to create smooth animations.

Let’s get started!