Javascript 等待 5 秒再执行下一行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14226803/
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
Wait 5 seconds before executing next line
提问by copyflake
This function below doesn't work like I want it to; being a JS novice I can't figure out why.
下面的这个功能不像我想要的那样工作;作为一个 JS 新手,我不明白为什么。
I need it to wait 5 seconds before checking whether the newStateis -1.
我需要它等待 5 秒钟,然后再检查是否newState是-1.
Currently, it doesn't wait, it just checks straight away.
目前,它不会等待,它会立即检查。
function stateChange(newState) {
setTimeout('', 5000);
if(newState == -1) {
alert('VIDEO HAS STOPPED');
}
}
回答by Joseph Silber
You have to put your code in the callback function you supply to setTimeout:
您必须将您的代码放在您提供给的回调函数中setTimeout:
function stateChange(newState) {
setTimeout(function () {
if (newState == -1) {
alert('VIDEO HAS STOPPED');
}
}, 5000);
}
Any other code will execute immediately.
任何其他代码将立即执行。
回答by Mic
You really shouldn't be doing this, the correct use of timeout is the right tool for the OP's problem and any other occasion where you just want to run something after a period of time. Joseph Silber has demonstrated that well in his answer. However, if in some non-production case you reallywant to hang the main thread for a period of time, this will do it.
您真的不应该这样做,正确使用超时是解决 OP 问题以及您只想在一段时间后运行某些内容的任何其他场合的正确工具。Joseph Silber 在他的回答中很好地证明了这一点。但是,如果在某些非生产情况下您确实想将主线程挂起一段时间,则可以这样做。
function wait(ms){
var start = new Date().getTime();
var end = start;
while(end < start + ms) {
end = new Date().getTime();
}
}
With execution in the form:
以以下形式执行:
console.log('before');
wait(7000); //7 seconds in milliseconds
console.log('after');
I've arrived here because I was building a simple test case for sequencing a mix of asynchronous operations around long-running blocking operations (i.e. expensive DOM manipulation) and this is my simulated blocking operation. It suits that job fine, so I thought I post it for anyone else who arrives here with a similar use case. Even so, it's creating a Date() object in a while loop, which might very overwhelm the GC if it runs long enough. But I can't emphasize enough, this is only suitable for testing, for building any actual functionality you should refer to Joseph Silber's answer.
我来到这里是因为我正在构建一个简单的测试用例,用于围绕长时间运行的阻塞操作(即昂贵的 DOM 操作)对异步操作的混合进行排序,这是我模拟的阻塞操作。它很适合这份工作,所以我想我将它发布给任何带着类似用例来到这里的人。即便如此,它还是在一个 while 循环中创建了一个 Date() 对象,如果它运行的时间足够长,这可能会使 GC 不堪重负。但我怎么强调都不为过,这仅适用于测试,要构建任何实际功能,您应该参考 Joseph Silber 的回答。
回答by Etienne Martin
Here's a solution using the new async/awaitsyntax.
这是使用新的async/await语法的解决方案。
Be sure to check browser supportas this is a new feature introduced with ECMAScript 6.
请务必检查浏览器支持,因为这是 ECMAScript 6 引入的新功能。
Utility function:
实用功能:
const delay = ms => new Promise(res => setTimeout(res, ms));
Usage:
用法:
const yourFunction = async () => {
await delay(5000);
console.log("Waited 5s");
await delay(5000);
console.log("Waited an additional 5s");
};
The advantage of this approach is that it makes your code look and behave like synchronous code.
这种方法的优点是它使您的代码看起来和行为类似于同步代码。
回答by jfriend00
You should not just try to pause 5 seconds in javascript. It doesn't work that way. You can schedule a function of code to run 5 seconds from now, but you have to put the code that you want to run later into a function and the rest of your code after that function will continue to run immediately.
您不应该只是尝试在 javascript 中暂停 5 秒。它不会那样工作。您可以安排一个代码函数从现在开始运行 5 秒,但是您必须将要稍后运行的代码放入一个函数中,并且该函数之后的其余代码将立即继续运行。
For example:
例如:
function stateChange(newState) {
setTimeout(function(){
if(newState == -1){alert('VIDEO HAS STOPPED');}
}, 5000);
}
But, if you have code like this:
但是,如果您有这样的代码:
stateChange(-1);
console.log("Hello");
The console.log()statement will run immediately. It will not wait until after the timeout fires in the stateChange()function. You cannot just pause javascript execution for a predetermined amount of time.
该console.log()语句将立即运行。它不会等到stateChange()函数中的超时触发之后。您不能只是在预定的时间内暂停 javascript 执行。
Instead, any code that you want to run delays must be inside the setTimeout()callback function (or called from that function).
相反,您想要运行延迟的任何代码都必须在setTimeout()回调函数内(或从该函数调用)。
If you did try to "pause" by looping, then you'd essentially "hang" the Javascript interpreter for a period of time. Because Javascript runs your code in only a single thread, when you're looping nothing else can run (no other event handlers can get called). So, looping waiting for some variable to change will never work because no other code can run to change that variable.
如果您确实尝试通过循环来“暂停”,那么您实际上会“挂起”Javascript 解释器一段时间。因为 Javascript 仅在单个线程中运行您的代码,所以当您循环时,其他任何东西都无法运行(无法调用其他事件处理程序)。因此,循环等待某个变量更改将永远不会起作用,因为没有其他代码可以运行来更改该变量。
回答by Kai Noack
Use a delay function like this:
使用这样的延迟函数:
var delay = ( function() {
var timer = 0;
return function(callback, ms) {
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
Usage:
用法:
delay(function(){
// do stuff
}, 5000 ); // end delay
Credits: How to delay the .keyup() handler until the user stops typing?
回答by Shl
If you're in an async functionyou can simply do it in one line:
如果你在一个异步函数中,你可以简单地在一行中完成:
console.log(1);
await new Promise(resolve => setTimeout(resolve, 3000)); // 3 sec
console.log(2);
Notice, if target is NodeJS it will be more efficient to use this (it's a predefined promisified setTimeout function):
注意,如果目标是 NodeJS,使用它会更有效(这是一个预定义的 promisified setTimeout 函数):
await setTimeout[Object.getOwnPropertySymbols(setTimeout)[0]](3000) // 3 sec
回答by Steve Jiang
Try this:
尝试这个:
//the code will execute in 1 3 5 7 9 seconds later
function exec() {
for(var i=0;i<5;i++) {
setTimeout(function() {
console.log(new Date()); //It's you code
},(i+i+1)*1000);
}
}
回答by Jitendra Pal - JP
Best way to create a function like this for wait in milli seconds, this function will wait for milliseconds provided in the argument:
以毫秒为单位创建这样一个函数的最佳方法,该函数将等待参数中提供的毫秒数:
function waitSeconds(iMilliSeconds) {
var counter= 0
, start = new Date().getTime()
, end = 0;
while (counter < iMilliSeconds) {
end = new Date().getTime();
counter = end - start;
}
}
回答by Sylhare
Based on Joseph Silber's answer, I would do it like that, a bit more generic.
根据 Joseph Silber 的回答,我会这样做,更通用一点。
You would have your function (let's create one based on the question):
你会有你的功能(让我们根据问题创建一个):
function videoStopped(newState){
if (newState == -1) {
alert('VIDEO HAS STOPPED');
}
}
And you could have a wait function:
你可以有一个等待功能:
function wait(milliseconds, foo, arg){
setTimeout(function () {
foo(arg); // will be executed after the specified time
}, milliseconds);
}
At the end you would have:
最后你会有:
wait(5000, videoStopped, newState);
That's a solution, I would rather not use arguments in the wait function (to have only foo();instead of foo(arg);) but that's for the example.
这是一个解决方案,我宁愿不在等待函数中使用参数(只有foo();而不是foo(arg);),但这是示例。
回答by bearacuda13
This solution comes from React Native's documentation for a refresh control:
此解决方案来自React Native 的刷新控件文档:
function wait(timeout) {
return new Promise(resolve => {
setTimeout(resolve, timeout);
});
}
To apply this to the OP's question, you could use this function in coordination with await:
要将其应用于 OP 的问题,您可以配合使用此功能await:
await wait(5000);
if (newState == -1) {
alert('Done');
}

