Reputation: 73
I have a series of jQuery functions to execute in a block. When they ALL are done, I need another function to be called. It seems a callback is the best way to do this. Here is my code.
function flipPage (x, callback) {
$("#view-1").animate({
width: x,
}, 500);
$("#view-2").animate({
width: browserWidth - x,
}, 500);
$("#iframe-2").animate({
left: -x,
}, 500);
$("#sweeper").animate({
left: x,
}, 500);
callback(function() {
alert("I'm Done.");
//do the next thing
}) ;
}
Upvotes: 0
Views: 103
Reputation: 5847
Essentially the same as sjkm's, but simplified.
function flipPage (x, callback) {
var counter = 0;
$("#view-1").animate({
width: x,
}, 500, finished);
$("#view-2").animate({
width: browserWidth - x,
}, 500, finished);
$("#iframe-2").animate({
left: -x,
}, 500, finished);
$("#sweeper").animate({
left: x,
}, 500, finished);
function finished() {
counter++;
if (counter >= 4) {
alert("I'm Done.");
//do the next thing if callback exists
callback && callback.call();
}
};
}
Upvotes: 0
Reputation: 3937
You could do something like this:
function flipPage (x, callback) {
var animationHelper = {
actionCounter: 0,
actionCount: 4,
callbackHandler: function() {
this.actionCounter++;
if(this.actionCounter == this.actionCount)
this.callbackAllFinished();
},
callbackAllFinished: null
};
$("#view-1").animate({
width: x }, 500, animationHelper.callbackHandler);
$("#view-2").animate({
width: browserWidth - x }, 500, animationHelper.callbackHandler);
$("#iframe-2").animate({
left: -x }, 500, animationHelper.callbackHandler);
$("#sweeper").animate({
left: x }, 500, animationHelper.callbackHandler);
animationHelper.callbackAllFinished = function() {
alert("I'm Done.");
//do the next thing
};
}
Upvotes: 2