我想在while循环中添加一个delay/sleep:

我是这样试的:

alert('hi');

for(var start = 1; start < 10; start++) {
  setTimeout(function () {
    alert('hello');
  }, 3000);
}

只有第一种情况是正确的:在显示alert('hi')后,它将等待3秒,然后alert('hello')将显示,但随后alert('hello')将不断重复。

我想要的是,在警报('hello')显示3秒后警报('hi'),然后它需要等待3秒的第二次警报('hello'),以此类推。


当前回答

下面是我如何创建一个无限循环的延迟,在特定条件下中断:

  // Now continuously check the app status until it's completed, 
  // failed or times out. The isFinished() will throw exception if
  // there is a failure.
  while (true) {
    let status = await this.api.getStatus(appId);
    if (isFinished(status)) {
      break;
    } else {
      // Delay before running the next loop iteration:
      await new Promise(resolve => setTimeout(resolve, 3000));
    }
  }

这里的关键是创建一个通过超时解析的新Promise,并等待它的解析。

显然你需要async/await支持。工作在Node 8。

其他回答

我只是想在这里发表我的意见。此函数运行具有延迟的迭代循环。请看这个jsfiddle。函数如下:

function timeout(range, time, callback){
    var i = range[0];                
    callback(i);
    Loop();
    function Loop(){
        setTimeout(function(){
            i++;
            if (i<range[1]){
                callback(i);
                Loop();
            }
        }, time*1000)
    } 
}

例如:

//This function prints the loop number every second
timeout([0, 5], 1, function(i){
    console.log(i);
});

相当于:

//This function prints the loop number instantly
for (var i = 0; i<5; i++){
    console.log(i);
}

如果使用ES6,你可以使用for循环来实现:

For(令I = 1;I < 10;我+ +){ setTimeout(函数定时器(){ console.log(“hello world”); }, I * 3000); }

它为每次迭代声明i,这意味着超时是+ 1000之前的超时。这样,传递给setTimeout的就是我们想要的。

setTimeout()函数是非阻塞的,将立即返回。因此,您的循环将非常快速地迭代,它将快速连续地启动一个接一个的3秒超时触发器。这就是为什么你的第一个警告会在3秒后弹出,而所有其他的警告都会紧随其后,没有任何延迟。

你可能想用这样的东西代替:

var i = 1; // set your counter to 1 function myLoop() { // create a loop function setTimeout(function() { // call a 3s setTimeout when the loop is called console.log('hello'); // your code here i++; // increment the counter if (i < 10) { // if the counter < 10, call the loop function myLoop(); // .. again which will trigger another } // .. setTimeout() }, 3000) } myLoop(); // start the loop

你也可以通过使用一个自调用函数,将迭代次数作为参数传递给它:

(函数myLoop(i) { setTimeout(函数(){ console.log('你好');//你的代码 if(——i) myLoop(i);//减少i,如果i > 0再次调用myLoop }, 3000) }) (10);//传递迭代次数作为参数

我用蓝鸟的承诺。延时和递归。

函数 myLoop(i) { 返回承诺延迟(1000) .then(function() { 如果 (i > 0) { 警报(“你好”); 返回 myLoop(i -= 1); } }); } 我的循环(3); <script src=“//cdnjs.cloudflare.com/ajax/libs/bluebird/2.9.4/bluebird.min.js”></script>

非常简单的单行解决方案,具有实际的异步等待延迟(没有排队setTimeout):

下面的(自动执行匿名)函数在循环之间创建一个实际的延迟,而不是具有不同超时的多个settimeout,这可能会弄乱内存。

在100个循环中的每一个循环中,它都等待一个新的承诺来解决。 这只发生在setTimeout '允许'它在90ms后。在此之前,代码将被async-await / pending Promise阻塞。

(async () => { For(令i=0;我< 100;我+ +){ 等待新的承诺((resolve) => {setTimeout(() =>{文档。我写(“${}”);解决(true)}, 90)}); } })()