Reputation: 87
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
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
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?
Upvotes: 1
Views: 88
Reputation: 2578
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);
}
}
Upvotes: 1
Reputation: 5249
The simplest way, without promises.
let i = 1
function timeout(){
i++
setTimeout(()=>{
console.log("Hai")
timeout()
},i % 5 === 0 ? 30000 : 1000)
}
timeout()
Upvotes: 1