Javascript – Canceling a Deferred Promise in jQuery

javascriptjqueryjquery-deferredpromise

How can I cancel a promise without removing the element from the DOM?

fiddle

I ran this code:

$("#box")
  .delay(2000)
  .show("slow")
  .delay(2000)
  .promise()                            
  .then(function(){log("Done");});

After this, is there a way to cancel the promise? Both clearQueue() and stop(true) didn't work, because it's not an animation that I'm trying to cancel. I saw that remove() should do it … but I only want to stop the promise, not remove the entire element.

Best Solution

Good news. Since yesterday you can cancel your promise.

I published the new version of my small plugin jquery-timing that provides two methods amongst many others called .wait() and .unwait().

var deferred = $("#box").delay(2000).show("slow").delay(2000).promise();
$.wait(deferred, function(){ log("Done"); });

If you then want to unregister the callback:

$.unwait();

These static versions of wait and unwait also support an optional group name to not cancel any handler but only a specific set.

Besides that you can do a lot more smart stuff like:

$('#box').wait(deferred).addClass('ready');

or the whole code in one chain, without unwait option:

$("#box").delay(2000).show("slow")
  .delay(2000).join(function(){log("Done");})).addClass('ready');

or the same even shorter with option to cancel the two pauses:

$("#box").wait(2000).show("slow",$)
  .wait(2000, function(){log("Done");})).addClass('ready');

Just see the docs, examples, and API what fits best for you.