promises
, a JavaScript feature of the ECMAScript 6
standard. If your target platform does not support promises
, polyfill it with PromiseJs.You can get the Deferred
object jQuery creates for the animation using .promise()
on the animation call. Wrapping these Deferreds
into ES6 Promises
results in much cleaner code than using timers.
You can also use Deferreds
directly, but this is generally discouraged because they do not follow the Promises/A+ specification.
The resulting code would look like this:
var p1 = Promise.resolve($('#Content').animate({ opacity: 0.5 }, { duration: 500, queue: false }).promise());
var p2 = Promise.resolve($('#Content').animate({ marginLeft: "-100px" }, { duration: 2000, queue: false }).promise());
Promise.all([p1, p2]).then(function () {
return $('#Content').animate({ width: 0 }, { duration: 500, queue: false }).promise();
});
Note that the function in Promise.all()
returns the promise. This is where magic happens. If in a then
call a promise is returned, the next then
call will wait for that promise to be resolved before executing.
jQuery uses an animation queue for each element. So animations on the same element are executed synchronously. In this case you wouldn't have to use promises at all!
I have disabled the jQuery animation queue to demonstrate how it would work with promises.
Promise.all()
takes an array of promises and creates a new Promise
that finishes after all promises in the array finished.
Promise.race()
also takes an array of promises, but finishes as soon as the first Promise
finished.