3

I was reading about jquery queue() here. The first answer is pretty comprehensive:

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

jsfiddle

I can't understand how next() (line 8) is working however. I get that if I comment it out the "next" confirm box fails to pop up until I press the button again, but I thought next() was used primarily for traversing the dom. Here though, it seems like it's telling the function to run again.

Also, if the queuing of the confirm boxes is within the each() function, why would they all be queued successfully without the next()?

Community
  • 1
  • 1
1252748
  • 14,597
  • 32
  • 109
  • 229

1 Answers1

3

next is a parameter in the callback function to queue. Do not confuse it with .next(), the jQuery collection method used for DOM navigation.

You can actually make the parameter anything you want in the callback as I demonstrate here. The name next is not particularly significant; it just makes sense in the documentation.

This parameter is itself a function (callback) that is passed to .queue by jQuery's internals.

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405