How to properly fire a callback after an animation and ajax calls have been successfully completed?
Well I have a AJAX calls being performed while I 开发者_开发知识库animate some content.
I want to fire a callback after both are finished successfully?
Any idea?
EDIT: fix typos in the title
This sounds like a good candidate for jQuery Deferred
Here's some rough code on how it would work.
function doAjax(){
return $.get('foo.htm'); // or $.ajax, $.getJSON.....etc
}
function doAnimation(){
var dfd = $.Deferred();
$("div").fadeIn(800).delay(1200).fadeOut(300, dfd.resolve);
return dfd.promise();
}
$.when( doAjax(), doAnimation() )
.then(function(){
console.log( 'I fire once BOTH have completed!' );
})
.fail(function(){
console.log( 'I fire if one or more requests failed.' );
});
Some references:
http://api.jquery.com/promise/
http://www.erichynds.com/jquery/using-deferreds-in-jquery/
As per some comments i checked to make sure both animation and ajax calls execute in parallel and as expected, they do. http://jsfiddle.net/Gdqfp/4/
How about something along the lines of this, where both success functions check that the other has finished using a global variable?
$.ajax({
url: 'http://fiddle.jshell.net/favicon.png',
beforeSend: function( xhr ) {
window.waitingforajax = true
},
success: function( ) {
window.waitingforajax = false;
if (window.waitingforanimation) {
myCallback();
}
}
});
window.waitingforanimation = true;
$('#book').animate({
opacity: 0.25,
left: '+=50',
height: 'toggle'
}, 5000, function() {
window.waitingforanimation= false;
if (window.waitingforajax) {
myCallback();
}
});
You can use
jQuery.when( animation, ajax ).then( success );
But that wont execute the methods at the same time. Another option is something like:
var stops = 2,
check = function() {
if (!--stops) {
alert('ready!');
}
};
$('#elem').animate({opacity:0}, check);
$.ajax('domain.com', check);
EDIT: appears that I was wrong. Try the $.when.then method, much cleaner!
精彩评论