简体   繁体   English

将回调推迟到setTimeout完成之前

[英]Deferring Callback until setTimeout has Completed

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? 你们中一位出色的SO天才能否向我解释一下为什么以下内容不起作用? 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. 我的意思是这样的complete的前调用回调函数setTimeout有内完成success的回调,我不明白为什么。

$.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? 是因为success回调中的setTimeout启动了新线程吗?

Is this possible to achieve without passing in a callback function into the success callback? 是否可以在不将回调函数传递到success回调的情况下实现?

It happens because setTimeout() does not block the execution of code. 发生这种情况是因为setTimeout()不会阻止代码的执行。

Therefore the complete callback fires at the same moment as it would without your call to setTimeout() . 因此, complete回调将在没有调用setTimeout()情况下同时触发。

You will have to put your console.log('ended'); 您将必须放置console.log('ended'); call into a timeout (too) or call your complete handler inside the timeout. 调用超时(太)或在超时内调用完整的处理程序。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM