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


当前回答

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

其他回答

const autoPlayer = (arr = [1, 2, 3, 4, 5]) => {
  // Base case:
  if (arr.length < 1) return

  // Remove the first element from the array.
  const item = arr.shift()

  // Set timout 
  setTimeout(() => {
    console.log('Hello, world!', item)  // Visualisation.
    autoPlayer() // Call function again.
  }, 1000) // Iterate every second.
}

Hey, I know this post is very old, but this code "loops" and adds a delay to it using a recursive method. I don't think you can 'actually' delay a loop itself from iterating based on reading various comments from other people. Maybe this can help someone out! Basically the function accepts an array (in this example). On each iteration the setTimeout Javascript method is called. The function calls itself again indefinitely when the timer of the setTimeout function expires, but on each call the array becomes smaller until it reaches the base-case. I hope this can help anyone else out.

简单实现了在循环运行期间每两秒显示一段文本。

for (var i = 0; i < foo.length; i++) {
   setInterval(function(){ 
     console.log("I will appear every 2 seconds"); 
   }, 2000);
  break;
};

var startIndex = 0; Var数据= [1,2,3]; Var超时= 1000; 函数functionToRun(i, length) { 警报(数据[我]); } (函数forWithDelay(i, length, fn, delay) { setTimeout(函数(){ fn(我、长度); 我+ +; If (i < length) { forWithDelay(i, length, fn, delay); } },延迟); }) (startIndex数据。length, functionToRun, timeout);

Daniel Vassallo回答的修改版本,将变量提取为参数,使函数更具可重用性:

首先让我们定义一些基本变量:

var startIndex = 0;
var data = [1, 2, 3];
var timeout = 3000;

接下来,您应该定义要运行的函数。这将传递i,循环的当前索引和循环的长度,以防你需要它:

function functionToRun(i, length) {
    alert(data[i]);
}

Self-executing版本

(function forWithDelay(i, length, fn, delay) {
   setTimeout(function () {
      fn(i, length);
      i++;
      if (i < length) {
         forWithDelay(i, length, fn, delay); 
      }
  }, delay);
})(startIndex, data.length, functionToRun, timeout);

功能版

function forWithDelay(i, length, fn, delay) {
   setTimeout(function () {
      fn(i, length);
      i++;
      if (i < length) {
         forWithDelay(i, length, fn, delay); 
      }
  }, delay);
}

forWithDelay(startIndex, data.length, functionToRun, timeout); // Lets run it

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

在ES6 (ECMAScript 2015)中,您可以使用生成器和间隔迭代延迟。

生成器(generator)是ECMAScript 6的一个新特性,是可以被替换的函数 顿了顿,接着说。调用genFunc不会执行它。相反,它 返回一个所谓的生成器对象,让我们控制genFunc的 执行。genFunc()最初是挂起在它的开始 的身体。方法genObj.next()继续执行genFunc, 直到下一次丰收。 (探索ES6)

代码示例: Let arr = [1,2,3, 'b']; let genObj = genFunc(); let val = genObj.next(); console.log (val.value); let interval = setInterval(() => { val = genObj.next(); If (val.done) { clearInterval(间隔); }其他{ console.log (val.value); } }, 1000); 函数* genFunc() { For (let item of arr) { 收益项; } }

所以如果你正在使用ES6,这是实现延迟循环的最优雅的方式(在我看来)。