I've spent much of the past couple of days trying to understand the point of queues. After reading the (largely unhelpful) documentation, reading several forum threads here and elsewhere, playing with several code snippets and finally digging through the source code, I think I've figured the point. Unfortunately, it's something that seems to be entirely missed in the documentation I have thus far found. It also seems to highlight some deficiencies in the existing design, so this may be a discussion more suited to the Developing jQuery Core forum, but as I'm still fairly new to jQuery, I thought I'd start here to perhaps get some more context first.
The first problem is that the documentation mentions that queues are used to manage asynchronous operations, which is kinda true, but misleading. The queues provide absolutely no asynchronous execution support at all. You can use them to help coordinate things that are happening asynchronously, but the actual asynchronous dispatch needs to be done elsewhere. In the case of animations, it's actually provided by fx objects and the timers array.
The next problem is that the documentation mentions that enqueued functions need to make sure that they call dequeue() - or better yet, the next() function that's passed to them. It doesn't however do anything to explain why or the context in which this was intended. This initially seemed rather strange to me, having come from platforms where queue management is provided by the infrastructure. You don't explicitly dequeue the next item as part of each enqueued function.
As I now understand it, the purpose of the existing design is specifically to support animations as follows:
- We enqueue an animation function.
- When dequeued, the animation function sets up the animation parameters and kicks off a timer via setInterval that periodically (every 13ms in jquery-1.4.4) updates the DOM object properties to achieve the animation.
- This may take several iterations, so can't be done in a synchronous call that is dequeued and executed, so when the animation is finished, it calls the next() function which essentially is how it indicates that this particular entry from the queue is done with so we can move on to the next.
If I've understood correctly, then great, but that I believe leads into a bunch of questions about improving the documentation and possibly enhancing the design and API to make some of the existing features useful. For instance, the option of using your own named queues seems a little pointless without some of the additional infrastructure.