On jQuery Animations + The Queue

One aspect of Hack Reactor that I've been particularly impressed with is the way the curriculum is structured; we're always learning multiple concepts. Today, we not only continued our exploration of BackboneJS, but also taught ourselves CoffeeScript. Early last week, we found ourselves refreshing our jQuery while learning about the different JavaScript instantiation patterns.

How did we do that? By coding up a dance party, with different dancers moving about the screen, each sharing some methods while having traits unique to their classes. This meant that my partner and I wrote code that had many animations going on at once, at different rates on a per-dancer basis.

This worked fine until we attempted to coordinate the movements of the dancers; then we found that some dancers would begin coordinating immediately, while others would only do so on a seemingly random delay. We quickly established that the most-delayed dancers were animating at the fastest rate, indicating to me that they were completing previously assigned animations before moving on to our command to coordinate.

However, despite many Google queries ("jQuery animations delay," "jQuery CSS animation not working," etc.), we were unable to find the solution, and the teachers at Hack Reactor were also stumped. We shelved the problem and worked on other parts of our implementation.

The next day, prompted by an unrelated statement by my partner, inspiration struck, and I Googled "jQuery clear animation stack." And there it was: the jQuery .clearQueue() method (and its cousin .stop()). It quickly and easily removes all the actions in the jQuery effects queue that have yet to be run. By running it on each dancer at the start of our coordinating functions, we were able to successfully sync objects that had been previously animating at different rates.

The moral of the story? If you're using many jQuery animations, keep .clearQueue() in mind.

Bradley Portnoy

Bradley Portnoy

I'm a recovering politico and brand marketer diving head-first into the world of software development, and always searching for ways to impact the world for the better.

View Comments