Search

API: queue & dequeue

Posted on 10th July 2009 — queue & dequeue are a pair of core data utilities that help you to add your own bespoke to animations.

Watch

Watch API: queue & dequeue screencast (Alternative flash version)

QuickTime version is approximately 7Mb, flash version is streaming.

View the demo used in the screencast

Queue & Dequeue

These methods tend to come in pairs when you’re working within the animation queue.

When you use the animate and show, hide, slideUp, etc effect methods, you’re adding a job on to the fx queue.

By default, using queue and passing a function, will add to the fx queue. So we’re creating our own bespoke animation step:

$('.box').animate({
  height : 20
}, 'slow')
.queue(function () {
  $('#title').html("We're in the animation, baby!");
});

As I said though, these methods come in pairs, so anything you add using queue, you need to dequeue to allow the process to continue. In the code above, if I chained more animations on, until I call $(this).dequeue(), the subsequent animations wouldn’t run:

$('.box').animate({
  height : 20
}, 'slow')
.queue(function () {
  $('#title').html("We're in the animation, baby!");
  $(this).dequeue();
})
.animate({
  height: 150
});

Keeping in mind that the animation won’t continue until we’ve explicitly called dequeue, we can easily create a pausing plugin, by adding a step in the queue that sets a timer and triggers after n milliseconds, at which time, it dequeues the element:

$.fn.pause = function (n) {
  return this.queue(function () {
    var el = this;
    setTimeout(function () {
      return $(el).dequeue();
    }, n);
  });
};

$('.box').animate({
  height : 20
}, 'slow')
.pause(1000) // 1000ms == 1 second
.animate({
  height: 150
});

Remember that the first argument for queue and dequeue are ‘fx’, and that in all of these examples I’m not including it because jQuery set the argument to ‘fx’ by default – so I don’t have to specify it.

You can see more examples on the jQuery documentation site for: queue & dequeue