简体   繁体   English

延迟javascript循环延迟

[英]delay in delay javascript looping

I have a loop that already has a delay like this 我有一个已经有这样延迟的循环

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

if using coding above it will be executed with a 1 second pause for 100 repetitions 如果使用上面的编码,它将暂停1秒执行100次重复

here I want to add one more delay where if it reaches 5 times it will pause longer eg 30 seconds then continue again before the delay 在这里我想增加一个延迟,如果达到5倍,它将暂停更长的时间,例如30秒,然后在延迟之前再次继续

example : 例如:

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

Is that possible? 那可能吗?

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

The simplest way, without promises. 最简单的方法,没有承诺。

let i = 1
function timeout(){
    i++
    setTimeout(()=>{
        console.log("Hai")
        timeout()
    },i % 5 === 0 ? 30000 : 1000)
}
timeout()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM