下面这个函数并没有像我想要的那样工作;作为一个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');
}
}
当前回答
您真的不应该这样做,正确使用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.
其他回答
你不应该只是尝试在javascript中暂停5秒。事情不是这样的。您可以安排一个代码函数从现在开始运行5秒,但是您必须将稍后要运行的代码放入一个函数中,并且该函数之后的其余代码将继续立即运行。
例如:
function stateChange(newState) {
setTimeout(function(){
if(newState == -1){alert('VIDEO HAS STOPPED');}
}, 5000);
}
但是,如果你有这样的代码:
stateChange(-1);
console.log("Hello");
console.log()语句将立即运行。它不会等到超时在stateChange()函数中触发之后。你不能只是在预定的时间内暂停javascript执行。
相反,任何想要运行延迟的代码都必须在setTimeout()回调函数中(或从该函数调用)。
如果您试图通过循环来“暂停”,那么您实际上是在“挂起”Javascript解释器一段时间。因为Javascript只在一个线程中运行代码,当循环时,其他任何东西都不能运行(不能调用其他事件处理程序)。因此,循环等待某个变量的改变永远不会起作用,因为没有其他代码可以运行来改变该变量。
创建这样一个以毫秒为单位等待的函数的最好方法是,这个函数将在参数中提供的毫秒内等待:
函数waitSeconds(imillisecseconds) { Var计数器= 0 , start = new Date().getTime() , end = 0; while (counter < imillisecseconds) { end = new Date().getTime(); Counter = end - start; } }
您可以通过对函数(async和await)进行一些小更改来增加延迟。
const addNSecondsDelay = (n) => {
return new Promise(resolve => {
setTimeout(() => {
resolve();
}, n * 1000);
});
}
const asyncFunctionCall = async () {
console.log("stpe-1");
await addNSecondsDelay(5);
console.log("step-2 after 5 seconds delay");
}
asyncFunctionCall();
试试这个:
//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);
}
}
像这样使用延迟函数:
var delay = ( function() {
var timer = 0;
return function(callback, ms) {
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
用法:
delay(function(){
// do stuff
}, 5000 ); // end delay
学分:如何延迟.keyup()处理程序,直到用户停止输入?