Asynchronous Javascript: Sequential Animations

Like many web developers, I like to play with animations. Most of the time I just want to transition a color, make a modal fade in, or translate an element in a straight line. In these situations, I feel that CSS is the right tool for the job. It allows you to get a lot done with not a lot of code, is generally straight forward to understand, and performs great (so long as you stick to animating properties like opacity and transform!). This being said, CSS may not have the firepower to handle animations that require a lot of calculation and logic – Javascript to the rescue!

Like Uncle Ben would say, “With great power comes great responsibility”, and you need to be responsible when using Javascript animations. There are many different ways to use Javascript to animate the DOM, and many of these methods will result in subpar animations that look choppy. Personally, I like to leave the optimizations to the experts and am happy to import Velocity.js to handle the details for me.

Much like HTTP requests, animations depend on resources external to the Javascript engine and won’t block the execution of subsequent lines of code. Here’s an example of what I mean:


If you go to codepen and check the console then you will see that the final line of code is allowed to run before the animation completes. While this is definitely the behaviour that we want, it is a bit trickier to manage than a purely synchronous program.

Much like with http requests, callback functions are the basic technique used to deal with this asynchronous behaviour. This, however, can get messy. For example, look at how the code might look if we wanted to do 5 animations in succession:


Not great right?

But when used in combination with jQuery, Velocity animations return promises! This feature allows us to layout long chains of animations in a more readable way. As a final exercise, checkout this animation of a basketball rolling around a perimeter. I think that it is a good example of one of the mathy, logic based animations that are well suited for Javascript!