How to Clear a Named Queue in jQuery
Managing asynchronous task sequences and custom animations in jQuery
often requires working with named queues. This article demonstrates how
to empty a specific named queue on selected elements, covering the
built-in .clearQueue() method and the alternative
.queue() technique with concise code examples.
Using the
.clearQueue() Method
The most direct way to remove all unexecuted functions from a named
queue is jQuery's .clearQueue() method. By default, calling
this method without parameters clears the standard animation queue
(fx), but passing the queue's name as a string targets that
specific custom sequence.
// Clear the custom queue named "myQueue" on a targeted element
$("#myElement").clearQueue("myQueue");When this runs, any functions waiting in "myQueue" are
removed immediately and will not execute.
Using the
.queue() Method with an Empty Array
An alternative approach is setting the named queue to an empty array
using the .queue() method. This explicitly replaces the
existing sequence array with a blank list.
// Replace the contents of "myQueue" with an empty array
$("#myElement").queue("myQueue", []);This method produces the same functional result as
.clearQueue("myQueue") and is compatible with older
versions of jQuery (prior to jQuery 1.4).
Important Considerations
Clearing a named queue only removes functions that are currently waiting in line. If a function from the queue is already actively executing, clearing the queue will not abort that running operation; it simply prevents the subsequent items in the sequence from being invoked.