下面这个函数并没有像我想要的那样工作;作为一个JS新手,我不明白为什么。
我需要它等待5秒,然后检查newState是否为-1。
目前,它不会等待,它只是直接检查。
function stateChange(newState) {
setTimeout('', 5000);
if(newState == -1) {
alert('VIDEO HAS STOPPED');
}
}
下面这个函数并没有像我想要的那样工作;作为一个JS新手,我不明白为什么。
我需要它等待5秒,然后检查newState是否为-1。
目前,它不会等待,它只是直接检查。
function stateChange(newState) {
setTimeout('', 5000);
if(newState == -1) {
alert('VIDEO HAS STOPPED');
}
}
当前回答
setTimeout(function() {
$('.message').hide();
}, 5000);
这将隐藏'。5秒后消息' div。
其他回答
您真的不应该这样做,正确使用timeout是解决OP问题的正确工具,以及任何其他您只想在一段时间后运行某些内容的情况。约瑟夫·西尔伯在他的回答中很好地证明了这一点。然而,如果在一些非生产的情况下,你真的想挂起主线程一段时间,这将做到这一点。
function wait(ms){
var start = new Date().getTime();
var end = start;
while(end < start + ms) {
end = new Date().getTime();
}
}
以以下形式执行:
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.
创建这样一个以毫秒为单位等待的函数的最好方法是,这个函数将在参数中提供的毫秒内等待:
函数waitSeconds(imillisecseconds) { Var计数器= 0 , start = new Date().getTime() , end = 0; while (counter < imillisecseconds) { end = new Date().getTime(); Counter = end - start; } }
根据约瑟夫·西尔伯的回答,我会这样做,更一般一点。
你会得到你的函数(让我们根据问题创建一个函数):
function videoStopped(newState){
if (newState == -1) {
alert('VIDEO HAS STOPPED');
}
}
你可以有一个等待函数:
function wait(milliseconds, foo, arg){
setTimeout(function () {
foo(arg); // will be executed after the specified time
}, milliseconds);
}
最后你会有:
wait(5000, videoStopped, newState);
这是一个解决方案,我宁愿不使用参数在等待函数(只有foo();而不是foo(arg);)但这只是例子。
这个解决方案来自React Native的刷新控件文档:
function wait(timeout) {
return new Promise(resolve => {
setTimeout(resolve, timeout);
});
}
要将此应用于OP的问题,您可以使用此函数与await配合使用:
await wait(5000);
if (newState == -1) {
alert('Done');
}
如果你在一个异步函数中,你可以简单地在一行中完成:
console.log(1);
await new Promise(resolve => setTimeout(resolve, 3000)); // 3 sec
console.log(2);
供你参考,如果目标是NodeJS,你可以使用这个内置函数(这是一个预定义的setTimeout函数):
import { setTimeout } from 'timers/promises';
await setTimeout(3000); // 3 sec