我想在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'),以此类推。


当前回答

这是可行的

for (var i = 0; i < 10; i++) {
  (function(i) {
    setTimeout(function() { console.log(i); }, 100 * i);
  })(i);
}

试试这把小提琴:https://jsfiddle.net/wgdx8zqq/

其他回答

这是可行的

for (var i = 0; i < 10; i++) {
  (function(i) {
    setTimeout(function() { console.log(i); }, 100 * i);
  })(i);
}

试试这把小提琴:https://jsfiddle.net/wgdx8zqq/

您可以创建一个承诺setTimeout的睡眠函数。这使您可以使用async/await来编写代码,而无需回调和熟悉的for循环控制流。

const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)); (async () => { 对于(设I = 0;I < 10;我+ +){ console.log(我); 等待睡眠(1000); } console.log(“完成”); }) ();

在Node中,你可以使用计时器/承诺来避免承诺步骤(如果旧版本的Node不支持该功能,上面的代码也可以工作):

const {setTimeout: sleep} = require("timers/promises");

// same code as above

无论如何,由于JS是单线程的,超时是异步的是一件好事。如果不这样做,浏览器就没有机会重新绘制UI,从而导致用户的界面冻结。

<!DOCTYPE html > < html > 身体< > <按钮onclick = " myFunction ()”> > < /按钮试试 < p id = "演示" > < / p > <脚本> 函数myFunction() { (var = 0;我< 5;我+ +){ Var sno = i+1; (函数myLoop (i) { setTimeout(函数(){ 警报(我);//在这里完成你的功能 }, 1000 *我); }) (sno); } } > < /脚本 < /身体> < / html >

   let counter =1;
   for(let item in items) {
        counter++;
        setTimeout(()=>{
          //your code
        },counter*5000); //5Sec delay between each iteration
    }

我认为你需要这样的东西:

var TimedQueue = function(defaultDelay){
    this.queue = [];
    this.index = 0;
    this.defaultDelay = defaultDelay || 3000;
};

TimedQueue.prototype = {
    add: function(fn, delay){
        this.queue.push({
            fn: fn,
            delay: delay
        });
    },
    run: function(index){
        (index || index === 0) && (this.index = index);
        this.next();
    },
    next: function(){
        var self = this
        , i = this.index++
        , at = this.queue[i]
        , next = this.queue[this.index]
        if(!at) return;
        at.fn();
        next && setTimeout(function(){
            self.next();
        }, next.delay||this.defaultDelay);
    },
    reset: function(){
        this.index = 0;
    }
}

测试代码:

var now = +new Date();

var x = new TimedQueue(2000);

x.add(function(){
    console.log('hey');
    console.log(+new Date() - now);
});
x.add(function(){
    console.log('ho');
    console.log(+new Date() - now);
}, 3000);
x.add(function(){
    console.log('bye');
    console.log(+new Date() - now);
});

x.run();

注意:使用警报暂停javascript执行,直到你关闭警报。 它的代码可能比您要求的要多,但这是一个健壮的可重用解决方案。