I have searched everywhere for a solution to this but have not been able to find anything thus far (I am probably using the wrong keywords! If this is a duplicate, please point out and I will delete).
Could one of you brilliant SO geniuses kindly explain to me why the following does not work as one would hope? What I mean by this is the complete callback is called before the setTimeout has completed within the success callback and I don't quite understand why.
$.ajax({
url: options.url,
data: options.data,
success: function(){
setTimeout(function(){
console.log('firing');
},2000);
},
dataType: options.dataType,
complete: function(){
console.log('ended');
}
});
Is it because a new thread has been started by the setTimeout within the success callback?
Is this possible to achieve without passing in a callback function into the success callback?
1 Answer 1
It happens because setTimeout() does not block the execution of code.
Therefore the complete callback fires at the same moment as it would without your call to setTimeout().
You will have to put your console.log('ended'); call into a timeout (too) or call your complete handler inside the timeout. :)
7 Comments
complete callback? In other words, does this not work simply because I am using setTimeout?complete callback is meant to be called once the success callback has completed! So how come this would not work?setTimeout, I only put it there for testing, if there was a lot of code within the success callback, and this code took, for sake of argument, 200ms to complete, would this defer the complete callback by 200ms?