javascript Javascript回调超时

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22690781/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 23:34:49  来源:igfitidea点击:

Javascript Callback timeout

javascriptcallback

提问by JunM

I have a fiddle here

这里有一个小提琴

Can someone help me understand why the first setTimeoutworks but not on secondone? Please see comments on the code.

有人能帮我理解为什么第一个setTimeout有效而不是second一个吗?请参阅代码注释。

In this case, I want to alert first I am firstthen after 6 seconds, it would alert Hello, sorry I am late

在这种情况下,我想先提醒,I am first然后在 6 秒后,它会提醒Hello, sorry I am late

function iAmTakingTooLong(message1, message2, callback){       
    //setTimeout(function(){ alert('test'); },6000); //THIS WILL WAIT FOR 6000 MILLISECONDS
    setTimeout(callback(message1+message2),6000);    //THIS WILL NOT WAIT FOR 6000 MILLISECONDS
}


iAmTakingTooLong('Hello, ', 'sorry I am late!', function(fullmessage){
    alert(fullmessage);
});

alert("I am first!");

回答by Pointy

In this code:

在这段代码中:

setTimeout(callback(message1+message2),6000);

you're callingthe callback function right there in the argument list. JavaScript evaluates function arguments before calling the function, so what actually gets passed to setTimeout()here is whatever the callback function returns.

您正在参数列表中调用回调函数。JavaScript 在调用函数之前评估函数参数,因此实际传递到setTimeout()这里的是回调函数返回的任何内容。

You need something like:

你需要这样的东西:

setTimeout(function() { callback(message1 + message2); }, 6000);

The behavior here is not unique to JavaScript.

这里的行为不是 JavaScript 独有的。