0

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?

asked Feb 8, 2013 at 10:21
0

1 Answer 1

5

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. :)

answered Feb 8, 2013 at 10:23
Sign up to request clarification or add additional context in comments.

7 Comments

That was quick +1, and exactly as I suspected! :-( If there wasn't a timeout within the callback, but instead a lot of code that took maybe 200ms to complete, would this defer the complete callback? In other words, does this not work simply because I am using setTimeout?
I must've misread before.. of course without the timeout complete would only be triggered after success spawns its "i am done" event. I believe you can solve your problem easily if you start thinking in terms of events. ;) simply define and trigger your own ones.
The complete callback is meant to be called once the success callback has completed! So how come this would not work?
It doesn't because complete has no idea about his setTimeout(). and it finishes after success is done setting up the timeout.
Ignore the 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?
|

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.