Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 56 ยท Effects and Animation

The Animation Queue

Understand the jQuery animation queue: chaining, .stop(), .finish(), .delay(), .queue(), .dequeue(), custom queues, hover pile-ups and .promise().

Run this in your head: $("#box").slideUp(300).fadeIn(300).animate({ left: 100 }, 300);. The three effects do not fight each other. They run one after another, because jQuery stores them in a queue attached to the element. The queue is why chained animations feel natural, and it is also the reason an impatient user who clicks a button ten times watches the box dance for several seconds after they stop.

This lesson shows how the queue works, how to stop or skip it, how to insert your own steps and how to find out when everything has finished.

One queue per element

Same element Effects wait their turn, in order.
Different elements Each has its own queue, so they run together.
1 / 2

How queueing works

Each element has a queue named "fx". Every effect method on that element (.animate(), .fadeIn(), .slideUp() and the rest) adds a step to the end. When one step finishes, the next starts. Different elements have separate queues, so effects on separate elements run at the same time.

JavaScript
$("#a").fadeOut(500).fadeIn(500);   // sequential on #a
$("#b").fadeOut(500);               // runs at the same time as #a's first step

There is one exception to "queued". The queue: false option starts an animation immediately instead of waiting, so two properties can move independently:

JavaScript
$("#box").animate({ left: 200 }, { duration: 600 });
$("#box").animate({ opacity: 0.3 }, { duration: 600, queue: false }); // starts now
Queued steps and a parallel one

In the bottom lane all three animations start together, so the final left: 6 fights the first left: 300. This is a deliberately messy picture: mixing queue: false with the same property is rarely what you want. Use it for different properties.

Pausing with .delay()

.delay(ms) adds a do-nothing step to the queue, so the next effect begins later.

JavaScript
$("#toast").fadeIn(200).delay(2000).fadeOut(400);

.delay() only affects the queue, not regular statements: $("#x").delay(500).addClass("ready") adds the class immediately because .addClass() is not an effect. For that case, put the call in the queue yourself (next sections) or use setTimeout.

Stopping: .stop()

.stop(clearQueue, jumpToEnd) halts the animation that is running right now. Both arguments default to false.

  • .stop() stops the current step where it is and moves on to the next queued step. That is usually not what you want.
  • .stop(true) stops the current step and clears the rest of the queue.
  • .stop(true, true) clears the queue and jumps the current step to its final state.

The classic use is a hover menu. Without .stop(), moving the mouse in and out repeatedly stacks slide steps, and the panel keeps bouncing after the mouse left. Stopping before starting the next animation fixes it.

JavaScript
$("#nav li").on("mouseenter", function () {
  $(this).find("ul").stop(true, true).slideDown(150);
}).on("mouseleave", function () {
  $(this).find("ul").stop(true, true).slideUp(150);
});

Prefer .stop(true, true) when a half-finished state would look wrong (a panel stuck at half height). Prefer .stop(true) when you want the element to turn around smoothly from wherever it is, such as a growing image that should shrink back from its current size.

Pile-up versus stop(true)

The left bar keeps going after the mouse leaves because dozens of steps are waiting. The counter makes that visible: .queue() with no arguments returns the array of waiting steps (the running one is shown as the string "inprogress").

Skipping to the end: .finish()

.finish() is the blunt instrument. It stops the current animation, runs every queued animation to its end state immediately, and clears the queue. Use it when you must be sure the element is in its final state, for example before reading its size.

JavaScript
$("#panel").slideUp(400).fadeIn(400).finish();   // ends up exactly as if both had completed

Your own steps: .queue() and .dequeue()

.queue(function (next) { ... }) inserts custom code into the effects queue. The function runs at its turn and must call next() (or $(this).dequeue()) when it is done, otherwise the queue stalls and everything behind it never runs.

JavaScript
$("#box")
  .fadeOut(300)
  .queue(function (next) {
    $(this).text("Back again!").css("background", "gold");
    next();
  })
  .fadeIn(300);

This is the right way to do "change something between two effects", because an ordinary line of code would run immediately.

Custom queues

You can use any name instead of "fx". Custom queues do not start by themselves: you must call .dequeue("name"). They are handy for sequences that should be controlled separately from visual effects, such as a list of tasks.

JavaScript
var $log = $("#log");
$log.queue("steps", function (next) { /* step 1 */ setTimeout(next, 300); });
$log.queue("steps", function (next) { /* step 2 */ next(); });
$log.dequeue("steps");   // starts the sequence

.clearQueue("steps") empties a queue without running it.

Custom steps inside an animation queue

Knowing when everything is done: .promise()

Per-element callbacks fire once for each element, which is awkward for a set. .promise() returns a promise that resolves when all queued actions on the matched set have finished, once.

JavaScript
$(".card").fadeOut(400);
$(".card").promise().done(function () {
  console.log("every card is gone");
});

Because it is an ordinary promise, you can combine it with others using $.when() (see Deferreds, Promises and Ajax Events):

JavaScript
$.when($("#a").slideUp().promise(), $("#b").fadeOut().promise()).done(function () {
  // both finished
});

jQuery 3 animations also work with native await, since the promise from .promise() is thenable: await $(".card").fadeOut(400).promise();.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Two different elements each call .fadeOut(500). How do they behave?

    The fx queue belongs to an element. Effects on different elements start together.
  2. 2. What is the difference between .stop() and .stop(true)?

    The first argument is clearQueue. Without it, the next queued animation begins immediately after the current one is stopped.
  3. 3. You add a custom function with .queue(function () { ... }) and never call next(). What happens?

    A queued function controls when the queue continues. If it neither calls next() nor $(this).dequeue(), the remaining steps wait forever.
  4. 4. Which method resolves once after all effects on a set of elements are complete?

    A complete callback runs per element. .promise() gives one promise for the whole set.

Summary

  • Effects on one element form a queue ("fx") and run in order; different elements run in parallel, and queue: false skips the line.
  • .delay(ms) pauses the queue between effects; it does not delay ordinary statements.
  • .stop(clearQueue, jumpToEnd) halts the running effect; use .stop(true) or .stop(true, true) to prevent hover pile-ups.
  • .finish() jumps every queued effect to its end state.
  • .queue(fn) inserts your own step (call next()!), custom queue names need .dequeue(name), and .promise() reports when all effects are done.

Next, we leave the browser-only world and talk to servers with AJAX with $.ajax().