我有一个已经有这样延迟的循环
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
有可能吗?
答案 0 :(得分:1)
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);
}
}
答案 1 :(得分:1)
最简单的方法,没有承诺。
let i = 1
function timeout(){
i++
setTimeout(()=>{
console.log("Hai")
timeout()
},i % 5 === 0 ? 30000 : 1000)
}
timeout()