SyntaxStudy
Sign Up
jQuery jQuery Animation Queue and Callbacks
jQuery Intermediate 6 min read

jQuery Animation Queue and Callbacks

jQuery maintains a per-element animation queue called fx. Each animation method adds itself to the queue and executes only after the previous animation completes. Understanding the queue lets you orchestrate complex multi-step sequences and control when animations play, pause, or reset.

Controlling the Queue

.stop() halts the currently running animation. Its two boolean arguments control whether to clear the remaining queue and whether to jump to the final state: .stop(clearQueue, jumpToEnd).

Custom Queue Steps

You can insert arbitrary functions into the animation queue using .queue(function(next){ ... next(); }). This lets you run non-animation code — like an AJAX call or a DOM update — in sequence with animations without breaking the queue flow.

  • .stop() — stop current animation, keep queue
  • .stop(true) — stop and clear remaining queue
  • .stop(true, true) — stop, clear, jump to end
  • .delay(ms) — pause the queue for ms milliseconds
  • .queue(fn) — insert a custom function into the queue
  • .dequeue() — manually advance the queue

Overuse of the queue can make UI feel sluggish. For user-triggered animations (hover, click) always call .stop(true) first to prevent a pile-up from rapid interactions.

Example
// Sequenced animations using the queue
$('#rocket')
    .animate({ bottom: '200px' }, 800)
    .delay(500)
    .animate({ opacity: 0 }, 400, function () {
        $(this).hide();
    });

// Insert a custom step mid-queue
$('#item')
    .animate({ left: '200px' }, 500)
    .queue(function (next) {
        $(this).addClass('highlighted');
        next(); // must call next to continue
    })
    .animate({ top: '100px' }, 500);

// Stop stacking on hover
$('.card').on('mouseenter', function () {
    $(this).stop(true).animate({ marginTop: '-=10px' }, 200);
}).on('mouseleave', function () {
    $(this).stop(true).animate({ marginTop: '0' }, 200);
});
Pro Tip

Insert custom logic between animations with .queue(fn) and always call next() to keep the queue flowing.