I cannot find delay
or wait
function for jQuery
promises. I have found one function on the SO (Using jQuery.Deferred to avoid nested setTimeout callbacks):
function delay(time) {
return function () {
console.log("Delaying");
var ret = new $.Deferred();
setTimeout(function () {
ret.resolve();
}, time);
return ret;
};
}
And, it's the way how I use it:
run: function () {
return $()
.promise()
.then(function () {
console.log("call together");
console.log("call together");
})
.then(delay(2000))
.then(function () {
console.log("call first");
})
.then(delay(2000))
.then(function () {
console.log("call second");
})
}
I want to extend promise or deferred object that I can write like:
run: function () {
return $()
.promise()
.then(function () {
console.log("call together");
console.log("call together");
})
.delay(2000)
.then(function () {
console.log("call first");
})
.delay(2000)
.then(function () {
console.log("call second");
})
}
Here is my solution. I wrap
$.Deferred(afterBuild)
and wrap originalafterBuild
that in turn wraps.promise(obj)
method, extending givenobj
with customdelay
method. Which useswindow.setTimeout
:Note: it only delays
done
branch.Edit, Updated
Try adding property
delay
tojQuery.Deferred
As @Bergi says jQuery Deferreds/Promises are not extendible by prototypal inheritance.
Instead, the model adopted by jQuery is to allow individual Promise instances to be extended with the syntax :
By defining a constructor with a bunch of methods, any jQuery Deferred or Promise can be extended with the simple syntax
In my unpublished, undocumented jQuery promises Playground, the constructor is named
$P
and kept in the jQuery namespace, hence the actual syntax I use is :You need to be aware of that, for the most part, it's not necessary to call
$.$P()
explicitly as the Playground includes a$.when_()
method that returns an already extended Promise.Here's an abbreviated version of the Playground with just enough to provide a
.delay()
method :The full Playground also includes a whole bunch more static and promise-instance methods for other purposes, and developing them is the essence of the play.
The ground-rules for using the Playgound are as follows :
$.when_()
, are made available just by installing the Playgound..when_()
, or chaining.promise($.$P())
..then_()
in place of.then()
.So here's how to use it to impose the delays required by the question :
DEMO
In the demo, the button's click handler gives further indication of how the Playground can be used.
Provisos on using the Playground :
And lastly, only consider the above if you are determined to implement delay with jQuery. It's far far simpler to use a promise lib that already has a
.delay()
method.