I found the jQuery.com document on queue()
/dequeue()
is too simple to understand. What exactly are queues in jQuery? How should I use them?
Jquery – What are queues in jQuery
jquery
jquery
I found the jQuery.com document on queue()
/dequeue()
is too simple to understand. What exactly are queues in jQuery? How should I use them?
Best Answer
The uses of jQuery
.queue()
and.dequeue()
Queues in jQuery are used for animations. You can use them for any purpose you like. They are an array of functions stored on a per element basis, using
jQuery.data()
. They are First-In-First-Out (FIFO). You can add a function to the queue by calling.queue()
, and you remove (by calling) the functions using.dequeue()
.To understand the internal jQuery queue functions, reading the source and looking at examples helps me out tremendously. One of the best examples of a queue function I've seen is
.delay()
:The default queue -
fx
The default queue in jQuery is
fx
. The default queue has some special properties that are not shared with other queues.$(elem).queue(function(){});
thefx
queue will automaticallydequeue
the next function and run it if the queue hasn't started.dequeue()
a function from thefx
queue, it willunshift()
(push into the first location of the array) the string"inprogress"
- which flags that the queue is currently being run.fx
queue is used by.animate()
and all functions that call it by default.NOTE: If you are using a custom queue, you must manually
.dequeue()
the functions, they will not auto start!Retrieving/Setting the queue
You can retrieve a reference to a jQuery queue by calling
.queue()
without a function argument. You can use the method if you want to see how many items are in the queue. You can usepush
,pop
,unshift
,shift
to manipulate the queue in place. You can replace the entire queue by passing an array to the.queue()
function.Quick Examples:
An animation (
fx
) queue example:Run example on jsFiddle
Another custom queue example
Run example on jsFiddle
Queueing Ajax Calls:
I developed an
$.ajaxQueue()
plugin that uses the$.Deferred
,.queue()
, and$.ajax()
to also pass back a promise that is resolved when the request completes. Another version of$.ajaxQueue
that still works in 1.4 is posted on my answer to Sequencing Ajax RequestsI have now added this as an article on learn.jquery.com, there are other great articles on that site about queues, go look.