在执行其余函数之前调用回调 [英] callback gets called before rest of the function executed

查看:76
本文介绍了在执行其余函数之前调用回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我重新创建了此示例(从下面给出的链接)以了解回调。问题在于回调是在父函数 first()完成之前执行的。 setTimeout可以正常工作,但回调方法要等到上述步骤之后再进行。如果我注释掉first()的第1行和第3行(即超时部分),则它以正确的顺序登录。

I recreated this example (from link given below) to understand callbacks. The problem is that the callback gets executed before the parent function 'first()' finishes. setTimeout works fine but callback doesn't wait until after the above . If i comment out line 1 and 3 of first() i.e. the timeout part, then it logs in the right order.

<script type="text/javascript">
function second() {
    console.log("second/callback function")
}

function first(callback){
    setTimeout(function(){
        console.log("first function")
    }, 1000 );
    callback();
}

first(second);

我误解了setTimeout的性质,请再举一个示例,其中可以看到回调正在等待。

链接:
https://codeburst.io/javascript-what-the-heck-is-a-callback-aba4da2deced

注意:我对JS的了解很少,实际上是在PHP中工作的,所以请给出一个简单的解释。谢谢

If this is working fine and i misunderstand the nature of setTimeout, then please give another example where the callback can be seen waiting.
Link: https://codeburst.io/javascript-what-the-heck-is-a-callback-aba4da2deced
Note: I know very little JS, was actually working in PHP, so kindly give a simple explanation. Thanks

推荐答案

看来您误解了 setTimeout()的工作方式。菲利普·罗伯茨(Philip Roberts)称为Loupe的工具可能会帮助您理解。我已经采取了你的代码放在它放入工具,它可以让你想象什么是真正发生的事情 - 的链接到放大镜

It appears that you misunderstand how setTimeout() works. This tool called Loupe by Philip Roberts may help you understand. I've taken your code placed it into the tool which will allow you to visualise what is actually happening - link to Loupe

当您使用 setTimeout 时,会提供该功能因为第一个参数会延迟第二个参数中提供的毫秒数(在您的示例中,这是 1000 )。您的其余代码将继续按顺序执行,直到超时为止。

When you use setTimeout, that function provided as the first parameter is delayed for the number of milliseconds provided in the second parameter (in your example, this is 1000). The rest of your code will continue to execute in order until this timeout has lapsed.

如果您要回调给定超时后执行的函数:您实际上可以这样写:

If you want your callback function to execute after the given timeout: you can actually just write it such like:

setTimeout(callback,1000)<-由于 callback 已经是一个函数,除非您希望在调用回调之前进行其他操作,否则无需将其包装在另一个函数中。

setTimeout(callback, 1000) <- Since callback is already a function, you don't need to wrap it in another function unless you wish to do other operations before calling the callback.

更新1(2018-10-26):

function second() {
    console.log("second/callback function")
}

function first(callback){
    console.log("first function")
    setTimeout(callback, 1000);
}

first(second);

这篇关于在执行其余函数之前调用回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆