Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<h2>The uses of jQuery <a href="http://api.jquery.com/queue/" rel="noreferrer"><code>.queue()</code></a> and <a href="http://api.jquery.com/dequeue/" rel="noreferrer"><code>.dequeue()</code></a></h2> <p><a href="http://en.wikipedia.org/wiki/Queue_%28data_structure%29" rel="noreferrer">Queues</a> in jQuery are used for animations. You can use them for any purpose you like. They are an <strong>array of functions</strong> stored on a per element basis, using <a href="http://api.jquery.com/jQuery.data" rel="noreferrer"><code>jQuery.data()</code></a>. They are First-In-First-Out (FIFO). You can add a function to the queue by calling <a href="http://api.jquery.com/queue" rel="noreferrer"><code>.queue()</code></a>, and you remove (by calling) the functions using <a href="http://api.jquery.com/dequeue" rel="noreferrer"><code>.dequeue()</code></a>.</p> <p>To understand the internal jQuery queue functions, <a href="http://github.com/jquery/jquery/blob/master/src/queue.js" rel="noreferrer">reading the source</a> and looking at examples helps me out tremendously. One of the best examples of a queue function I've seen is <a href="http://api.jquery.com/delay" rel="noreferrer"><code>.delay()</code></a>:</p> <pre><code>$.fn.delay = function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[time] || time : time; type = type || "fx"; return this.queue( type, function() { var elem = this; setTimeout(function() { jQuery.dequeue( elem, type ); }, time ); }); }; </code></pre> <h2>The default queue - <code>fx</code></h2> <p>The default queue in jQuery is <code>fx</code>. The default queue has some special properties that are not shared with other queues.</p> <ol> <li><strong>Auto Start:</strong> When calling <code>$(elem).queue(function(){});</code> the <code>fx</code> queue will automatically <code>dequeue</code> the next function and run it if the queue hasn't started. </li> <li><strong>'inprogress' sentinel:</strong> Whenever you <code>dequeue()</code> a function from the <code>fx</code> queue, it will <code>unshift()</code> (push into the first location of the array) the string <code>"inprogress"</code> - which flags that the queue is currently being run.</li> <li><strong>It's the default!</strong> The <code>fx</code> queue is used by <code>.animate()</code> and all functions that call it by default.</li> </ol> <p><strong>NOTE:</strong> If you are using a custom queue, you must manually <code>.dequeue()</code> the functions, they will not auto start!</p> <h2>Retrieving/Setting the queue</h2> <p>You can retrieve a reference to a jQuery queue by calling <code>.queue()</code> without a function argument. You can use the method if you want to see how many items are in the queue. You can use <code>push</code>, <code>pop</code>, <code>unshift</code>, <code>shift</code> to manipulate the queue in place. You can replace the entire queue by passing an array to the <code>.queue()</code> function.</p> <p><strong>Quick Examples:</strong></p> <pre><code>// lets assume $elem is a jQuery object that points to some element we are animating. var queue = $elem.queue(); // remove the last function from the animation queue. var lastFunc = queue.pop(); // insert it at the beginning: queue.unshift(lastFunc); // replace queue with the first three items in the queue $elem.queue(queue.slice(0,3)); </code></pre> <h2>An animation (<code>fx</code>) queue example:</h2> <p><a href="http://jsfiddle.net/evRG5/3/embedded/result" rel="noreferrer">Run example on jsFiddle</a></p> <pre><code>$(function() { // lets do something with google maps: var $map = $("#map_canvas"); var myLatlng = new google.maps.LatLng(-34.397, 150.644); var myOptions = {zoom: 8, center: myLatlng, mapTypeId: google.maps.MapTypeId.ROADMAP}; var geocoder = new google.maps.Geocoder(); var map = new google.maps.Map($map[0], myOptions); var resized = function() { // simple animation callback - let maps know we resized google.maps.event.trigger(map, 'resize'); }; // wait 2 seconds $map.delay(2000); // resize the div: $map.animate({ width: 250, height: 250, marginLeft: 250, marginTop:250 }, resized); // geocode something $map.queue(function(next) { // find stackoverflow's whois address: geocoder.geocode({'address': '55 Broadway New York NY 10006'},handleResponse); function handleResponse(results, status) { if (status == google.maps.GeocoderStatus.OK) { var location = results[0].geometry.location; map.setZoom(13); map.setCenter(location); new google.maps.Marker({ map: map, position: location }); } // geocoder result returned, continue with animations: next(); } }); // after we find stack overflow, wait 3 more seconds $map.delay(3000); // and resize the map again $map.animate({ width: 500, height: 500, marginLeft:0, marginTop: 0 }, resized); }); </code></pre> <h2>Another custom queue example</h2> <p><a href="http://jsfiddle.net/mkBJk/embedded/result" rel="noreferrer">Run example on jsFiddle</a></p> <pre><code>var theQueue = $({}); // jQuery on an empty object - a perfect queue holder $.each([1,2,3],function(i, num) { // lets add some really simple functions to a queue: theQueue.queue('alerts', function(next) { // show something, and if they hit "yes", run the next function. if (confirm('index:'+i+' = '+num+'\nRun the next function?')) { next(); } }); }); // create a button to run the queue: $("&lt;button&gt;", { text: 'Run Queue', click: function() { theQueue.dequeue('alerts'); } }).appendTo('body'); // create a button to show the length: $("&lt;button&gt;", { text: 'Show Length', click: function() { alert(theQueue.queue('alerts').length); } }).appendTo('body'); </code></pre> <h2>Queueing Ajax Calls:</h2> <p>I developed an <a href="http://gnarf.net/2011/06/21/jquery-ajaxqueue/" rel="noreferrer"><code>$.ajaxQueue()</code></a> plugin that uses the <a href="http://api.jquery.com/jQuery.Deferred" rel="noreferrer"><code>$.Deferred</code></a>, <a href="http://api.jquery.com/queue" rel="noreferrer"><code>.queue()</code></a>, and <a href="http://api.jquery.com/jQuery.ajax" rel="noreferrer"><code>$.ajax()</code></a> to also pass back a <a href="http://api.jquery.com/Types/#Promise" rel="noreferrer">promise</a> that is resolved when the request completes. Another version of <code>$.ajaxQueue</code> that still works in 1.4 is posted on my answer to <a href="https://stackoverflow.com/questions/3034874/sequencing-ajax-requests/3035268#3035268">Sequencing Ajax Requests</a></p> <pre><code>/* * jQuery.ajaxQueue - A queue for ajax requests * * (c) 2011 Corey Frang * Dual licensed under the MIT and GPL licenses. * * Requires jQuery 1.5+ */ (function($) { // jQuery on an empty object, we are going to use this as our Queue var ajaxQueue = $({}); $.ajaxQueue = function( ajaxOpts ) { var jqXHR, dfd = $.Deferred(), promise = dfd.promise(); // queue our ajax request ajaxQueue.queue( doRequest ); // add the abort method promise.abort = function( statusText ) { // proxy abort to the jqXHR if it is active if ( jqXHR ) { return jqXHR.abort( statusText ); } // if there wasn't already a jqXHR we need to remove from queue var queue = ajaxQueue.queue(), index = $.inArray( doRequest, queue ); if ( index &gt; -1 ) { queue.splice( index, 1 ); } // and then reject the deferred dfd.rejectWith( ajaxOpts.context || ajaxOpts, [ promise, statusText, "" ] ); return promise; }; // run the actual query function doRequest( next ) { jqXHR = $.ajax( ajaxOpts ) .done( dfd.resolve ) .fail( dfd.reject ) .then( next, next ); } return promise; }; })(jQuery); </code></pre> <hr> <p><em>I have now added this as an article on <a href="http://learn.jquery.com/effects/uses-of-queue-and-dequeue/" rel="noreferrer">learn.jquery.com</a>, there are other great articles on that site about queues, go look.</em></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload