我有一个已经有这样延迟的循环

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


如果使用上面的编码,它将暂停1秒执行100次重复

在这里我想增加一个延迟,如果达到5倍,它将暂停更长的时间,例如30秒,然后在延迟之前再次继续

例如:

Hai .. delay 1 second
Hai .. delay 1 second
Hai .. delay 1 second
Hai .. delay 1 second
Hai .. delay 1 second
delay 30 second
Hai .. delay 1 second
Hai .. delay 1 second
Hai .. delay 1 second
Hai .. delay 1 second
Hai .. delay 1 second


那可能吗?

最佳答案

const timeout = ms => new Promise(res => setTimeout(res, ms))
async function sayHai() {
  for (var i = 0; i < 100; i++) {
      await timeout(1000);
      console.log("Hai");
      if ( (i%5) == 4 ) await timeout(30000);
  }
}

07-28 11:03