下面这个函数并没有像我想要的那样工作;作为一个JS新手,我不明白为什么。

我需要它等待5秒,然后检查newState是否为-1。

目前,它不会等待,它只是直接检查。

function stateChange(newState) {
  setTimeout('', 5000);

  if(newState == -1) {
    alert('VIDEO HAS STOPPED');
  }
}

当前回答

试试这个:

//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);
    }
}

其他回答

根据约瑟夫·西尔伯的回答,我会这样做,更一般一点。

你会得到你的函数(让我们根据问题创建一个函数):

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);)但这只是例子。

setTimeout(function() {
     $('.message').hide();
}, 5000);

这将隐藏'。5秒后消息' div。

像这样使用延迟函数:

var delay = ( function() {
    var timer = 0;
    return function(callback, ms) {
        clearTimeout (timer);
        timer = setTimeout(callback, ms);
    };
})();

用法:

delay(function(){
    // do stuff
}, 5000 ); // end delay

学分:如何延迟.keyup()处理程序,直到用户停止输入?

试试这个:

//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);
    }
}

您可以通过对函数(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();