Javascript wait() 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15694470/
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 01:45:07  来源:igfitidea点击:

Javascript wait() function

javascriptfunctionwait

提问by eds1999

I want to create a JavaScript wait()function.

我想创建一个 JavaScriptwait()函数。

What should I edit?

我应该编辑什么?

function wait(waitsecs) {
    setTimeout(donothing(), 'waitsecs');
}

function donothing() {
    //
}

回答by Dave

Javascript isn't threaded, so a "wait" would freeze the entire page (and probably cause the browser to stop running the script entirely).

Javascript 没有线程化,因此“等待”会冻结整个页面(并且可能导致浏览器完全停止运行脚本)。

To specifically address your problem, you should remove the brackets after donothingin your setTimeoutcall, and make waitsecsa number not a string:

要专门解决您的问题,您应该donothingsetTimeout调用后删除括号,并创建waitsecs一个数字而不是字符串:

console.log('before');
setTimeout(donothing,500); // run donothing after 0.5 seconds
console.log('after');

But that won't stop execution; "after" will be logged before your function runs.

但这不会停止执行;“after”将在您的函数运行之前记录。

To wait properly, you can use anonymous functions:

要正确等待,您可以使用匿名函数:

console.log('before');
setTimeout(function(){
    console.log('after');
},500);

All your variables will still be there in the "after" section. You shouldn't chain these - if you find yourself needing to, you need to look at how you're structuring the program. Also you may want to use setInterval/ clearIntervalif it needs to loop.

您的所有变量仍将在“之后”部分中。你不应该链接这些 - 如果你发现自己需要,你需要看看你是如何构建程序的。如果需要循环,您也可能想使用setInterval/ clearInterval

回答by Niet the Dark Absol

You shouldn't edit it, you should completely scrap it.

你不应该编辑它,你应该完全废弃它。

Any attempt to make execution stop for a certain amount of time will lock up the browser and switch it to a Not Responding state. The only thing you can do is use setTimeoutcorrectly.

任何使执行停止一段时间的尝试都会锁定浏览器并将其切换到“无响应”状态。你唯一能做的就是setTimeout正确使用。