Using a Queue

One way to make asynchronous functions run sequentially is to use a queue - this is what a queue is for and the default queue is used to make animations run sequentially on a single element.

Is there any way we could use a queue to make animations on different elements run sequentially?

Of course there is as long as we are careful about when we call the next function. It has to be called when the animation is complete.

First we need a custom queue that can be used to queue animations on different elements. Note that each element will still have its own default queue that makes the animations run sequentially this is an additional queue that makes the animations on different elements run sequentially.

First we need an object that we can use as a universal queue.

var seq = $({});

This object can support multiple queues if necessary but in this example we will just use one "q1". The first thing we have to do is add a function that runs the animation:

When it gets to run this causes the animation on button1 to start and this runs sequentially on the default queue. The only tricky bit is where to place the call to next. This is placed as the complete function in the final animation and this causes the next item in q1 to be dequeued.

You can do the same thing with the animation on another element and finally to get q1 started we need to make an explicit call to dequeue. For example:

If you run this you will see button1 animate and then button2 animates.

Once you have seen the method you can see that it can be generalized to start other animations at particular points in an animation. For example if you wanted to start the second button's animation at the end of the first slide up you would change the code to:

You can even start multiple animations at different points by calling next more than once.

jQuery For Animation?

There are more extensive libraries that are designed to make animation easy and polished. jQuery gives you some basic tools to create a fairly simple animated UI. Think of it as being something that is there as a part of using jQuery and something that you can use with little extra cost to add a bit of polish to the UI. If you plan to make animation a key part of the UI, or want to use animation in a game or something similar, then jQuery is almost certainly not sufficient for your purpose.

There are many ways in which JavaScript's approach is different from standard, run of the mill, class-based languages, but some of them go unnoticed. Take the whole subject of parameter passing - Java [ ... ]

One of jQuery's attractive features is the way that you can build up chains of commands that look almost like the way you would use a language. This is more generally called a "Fluent Interface" and i [ ... ]