Reputation: 53
I've got x number of animations running on a random timer. I also have code that needs to run after all the animations are complete.
I thought to use deferred, but it doesn't seem to be running the way I hoped it was going to. Here's a link (you may have to run it a few times for it to not work):
Code:
var callback = function() {
alert('done!');
};
var animations;
for (var i = 0; i < $('div').length; i++) {
var random = Math.random() * (800 - 100) + 100;
animations = $('div').eq(i).slideUp(random);
}
$.when(animations).done(callback);
Any suggestions on how to wait for the callback to be called once all the animations are complete?
Upvotes: 3
Views: 290
Reputation: 816462
You are always overriding the animations
variable. So the object you pass to $.when
will be the one from the last iteration.
Add them to an array and call $.when
with that array:
var animations = [];
for (var i = 0; i < $('div').length; i++) {
var random = Math.random() * (800 - 100) + 100;
animations.push($('div').eq(i).slideUp(random));
}
$.when.apply($, animations).done(callback);
Reference: .apply
Upvotes: 4