It will be easier for you:
- make
animationAgent() simple by promising a returning working function that knows only about the element that it animates, and nothing about the sequence in which it should be used (i.e. omit prevElement ), - we organize the functions
f1() , f2() and f3() to return the promise returned by him, animationAgent() .
Then you have the basis for creating a reliable animation sequence.
function animationAgent(element) { return $(element).css("display", "block").animate({width:360}, 2000, "linear").promise(); } function f1() { return animationAgent("#div1"); } function f2() { return animationAgent("#div2"); } function f3() { return animationAgent("#div3"); } f1().then(f2).then(f3);
Demo
Alternatively, mechanically build a .then chain from an array of function references:
function animationAgent(element) { return $(element).css("display", "block").animate({width:360}, 2000, "linear").promise(); } function f1() { return animationAgent("#div1"); } function f2() { return animationAgent("#div2"); } function f3() { return animationAgent("#div3"); } [f1, f2, f3].reduce(function(promise, fn) { return promise.then(function() { return fn(); }); }, $.when());
Demo
Or, since the three animations are identical, you can avoid the need for separate functions by building a .then chain from an array of element selectors and directly calling animationAgent() :
function animationAgent(element) { return $(element).css("display", "block").animate({width:360}, 2000, "linear").promise(); } ['#div1', '#div2', '#div3'].reduce(function(promise, selector) { return promise.then(function() { return animationAgent(selector); }); }, $.when());
Demo
Roamer-1888
source share