What is a queue in jQuery?

I found on queue ()/ dequeue () jQuery The.com documentation is too simple.What exactly is a queue in jQuery?How should I use them?

#1st floor

It allows you to queue an animation...for example, instead of this

$('#my-element').animate( { opacity: 0.2, width: '100px' }, 2000);

It decays elements and makes them 100 pixels wide at the same time.Use queues to animate onstage.So, one by one.

$("#show").click(function () {
    var n = $("div").queue("fx");
    $("span").text("Queue length is: " + n.length);
});

function runIt() {
    $("div").show("slow");
    $("div").animate({left:'+=200'},2000);
    $("div").slideToggle(1000);
    $("div").slideToggle("fast");
    $("div").animate({left:'-=200'},1500);
    $("div").hide("slow");
    $("div").show(1200);
    $("div").slideUp("normal", runIt);
}
runIt();

Come from http://docs.jquery.com/Effects/queue Example

#2nd floor

To understand the queue method, you must understand how jQuery animates.If you write multiple animation method calls one by one, jQuery creates an "internal" queue and adds these method calls to it.It then runs those animation calls one by one.

Consider the following code.

function nonStopAnimation()
{
    //These multiple animate calls are queued to run one after
    //the other by jQuery.
    //This is the reason that nonStopAnimation method will return immeidately
    //after queuing these calls. 
    $('#box').animate({ left: '+=500'}, 4000);
    $('#box').animate({ top: '+=500'}, 4000);
    $('#box').animate({ left: '-=500'}, 4000);

    //By calling the same function at the end of last animation, we can
    //create non stop animation. 
    $('#box').animate({ top: '-=500'}, 4000 , nonStopAnimation);
}

With the Queue/Out method, you can control this Animation Queue.

By default, the name of the animation queue is "fx".I've created a sample page here that contains examples of how to use queue methods.

http://jsbin.com/zoluge/1/edit?html, output

Code for the example page above:

$(document).ready(function() {
    $('#nonStopAnimation').click(nonStopAnimation);

    $('#stopAnimationQueue').click(function() {
        //By default all animation for particular 'selector'
        //are queued in queue named 'fx'.
        //By clearning that queue, you can stop the animation.
        $('#box').queue('fx', []);
    });

    $('#addAnimation').click(function() {
        $('#box').queue(function() {
            $(this).animate({ height : '-=25'}, 2000);
            //De-queue our newly queued function so that queues
            //can keep running.
            $(this).dequeue();
        });
    });

    $('#stopAnimation').click(function() {
        $('#box').stop();
    });

    setInterval(function() {
        $('#currentQueueLength').html(
         'Current Animation Queue Length for #box ' + 
          $('#box').queue('fx').length
        );
    }, 2000);
});

function nonStopAnimation()
{
    //These multiple animate calls are queued to run one after
    //the other by jQuery.
    $('#box').animate({ left: '+=500'}, 4000);
    $('#box').animate({ top: '+=500'}, 4000);
    $('#box').animate({ left: '-=500'}, 4000);
    $('#box').animate({ top: '-=500'}, 4000, nonStopAnimation);
}

Now you might ask, why do I interrupt this queue?Normally, you don't.However, if you want to control complex animation sequences, the queue/queue method is your friend.

See also an interesting conversation about the jQuery group about creating complex animation sequences.

http://groups.google.com/group/jquery-zh-CN/browse_thread/thread/b398ad505a9b0512/f4f3e841eab5f5a2?lnk=gst

Animation demo:

http://www.exfer.net/test/jquery/tabslide/

Let me know if you have any questions.

#3rd floor

The functions makeRed and makeBlack use queue and dequeue to execute each other.The effect is that the'wow'element blinks continuously.

<html>
  <head>
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script type="text/javascript">
      $(document).ready(function(){
          $('#wow').click(function(){
            $(this).delay(200).queue(makeRed);
            });
          });

      function makeRed(){
        $('#wow').css('color', 'red');
        $('#wow').delay(200).queue(makeBlack);
        $('#wow').dequeue();
      }

      function makeBlack(){
        $('#wow').css('color', 'black');
        $('#wow').delay(200).queue(makeRed);
        $('#wow').dequeue();
      }
    </script>
  </head>
  <body>
    <div id="wow"><p>wow</p></div>
  </body>
</html>

#4th floor

jQuery .queue() and .dequeue()

In jQuery queue For animation.You can use them for any purpose you like.They are used jQuery.data() An array of functions stored on the basis of each element.They are FIFO.You can call .queue() Add a function to the queue and use .dequeue() Delete (by calling) a function.

To understand the internal jQuery queue functionality, Read the source code And view examples Will I was very helpful.One of the best examples of queue functions I've ever seen is .delay() :

$.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 );
  });
};

Default queue fx

The default queue in jQuery is fx.Default queues have special properties that are not shared with other queues.

  1. Autostart: Call $(elem).queue(function(){}); if the queue has not been started, the fx queue will automatically make the next function dequeue and run it.
  2. "Inprogress" Sentry: Whenever you dequeue() function dequeue() from fx queue, it will unshift() (push it to the first position in the array) string "inprogress" - indicating that the queue is currently running.
  3. This is the default value!.animate() and all functions that call it by default use the fx queue.

Note: If you are using custom queues, you must use the manual.dequeue() function, which will not start automatically!

Retrieve/Set Queue

You can retrieve a reference to a jQuery queue by calling.queue() without a function parameter.If you want to see how many items are in the queue, you can use this method.You can use push, pop, unshift, shift to manipulate the queue.You can replace the entire queue by passing the array to the.queue() function.

Quick examples:

// 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)); 

Example of an animation (fx) queue:

Run the sample on jsFiddle

$(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);
});

Another example of a custom queue

Run the sample on jsFiddle

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:
$("<button>", {
  text: 'Run Queue', 
  click: function() { 
    theQueue.dequeue('alerts'); 
  }
}).appendTo('body');

// create a button to show the length:
$("<button>", {
  text: 'Show Length', 
  click: function() { 
    alert(theQueue.queue('alerts').length); 
  }
}).appendTo('body');

Queue Ajax calls:

I developed a $.ajaxQueue() Plug-in, which uses $.Deferred.queue() and $.ajax() To pass a request that has been resolved after completion Promise .I am right Sequencing Ajax Requests Another version of $.ajaxQueue that can still be used in 1.4 is published in the answer.

/*
* 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 > -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);

Now I add it as On learn.jquery.com Articles, there are other great articles about queues on this website, please check them out.

#5th floor

This thread was very helpful to my problem, but I used $.queue differently and thought I would post my thoughts here.What I need is a sequence of events (frames) to trigger, but to build it dynamically.I have a different number of placeholders, each of which should contain an image of the animation sequence.The data is stored in the array array, so I iterate through the array to build each sequence for each placeholder, as follows:

/* create an empty queue */
var theQueue = $({});
/* loop through the data array */
for (var i = 0; i < ph.length; i++) {
    for (var l = 0; l < ph[i].length; l++) {
        /* create a function which swaps an image, and calls the next function in the queue */
        theQueue.queue("anim", new Function("cb", "$('ph_"+i+"' img').attr('src', '/images/"+i+"/"+l+".png');cb();"));
        /* set the animation speed */
        theQueue.delay(200,'anim');
    }
}
/* start the animation */
theQueue.dequeue('anim');

This is a simplified version of the script I arrived at, but it should show how - when adding a function to a queue, use the Function constructor to add it - so that you can write a function (s) dynamically using variables in a loop.Note how the function is passed to next() to invoke the parameter and call it at the end.The function in this case is not time dependent (it doesn't use $.fadeIn or something like that), so I use $.delay interlacing.

#6th floor

Animation of multiple objects in a queue

This is a simple example of animating multiple objects in a queue.

jQuery allows us to queue only one object.But in animation, we can access other objects.In this example, we set a queue on the #q object and animate the #box1 and #box2 objects at the same time.

Consider the queue as an array of functions.Therefore, you can manipulate the queue as an array.You can manipulate the queue by pushing, ejecting, not shifting, or shifting.In this example, we delete the last function from the animation queue and insert it at the beginning.

When finished, we launch the animation queue through the dequeue() function.

See jsFiddle

HTML:

  <button id="show">Start Animation Queue</button>
  <p></p>
  <div id="box1"></div>
  <div id="box2"></div>
  <div id="q"></div>

js:

$(function(){

 $('#q').queue('chain',function(next){  
      $("#box2").show("slow", next);
  });


  $('#q').queue('chain',function(next){  
      $('#box1').animate(
          {left: 60}, {duration:1000, queue:false, complete: next}
      )
  });    


  $('#q').queue('chain',function(next){  
      $("#box1").animate({top:'200'},1500, next);
  });


  $('#q').queue('chain',function(next){  
      $("#box2").animate({top:'200'},1500, next);
  });


  $('#q').queue('chain',function(next){  
      $("#box2").animate({left:'200'},1500, next);
  });

  //notice that show effect comes last
  $('#q').queue('chain',function(next){  
      $("#box1").show("slow", next);
  });

});

$("#show").click(function () {
    $("p").text("Queue length is: " + $('#q').queue("chain").length);

    // remove the last function from the animation queue.
    var lastFunc = $('#q').queue("chain").pop();
    // insert it at the beginning:    
    $('#q').queue("chain").unshift(lastFunc);

    //start animation queue
    $('#q').dequeue('chain');
});

CSS:

        #box1 { margin:3px; width:40px; height:40px;
                position:absolute; left:10px; top:60px; 
                background:green; display: none; }
        #box2 { margin:3px; width:40px; height:40px;
                position:absolute; left:100px; top:60px; 
                background:red; display: none; }
        p { color:red; }  
0 original articles published. 2. 10,000 visits+
Private letter follow

Tags: JQuery Google Javascript

Posted on Tue, 11 Feb 2020 18:17:52 -0800 by newman