1

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?

3
  • That is so bad way of doing it, you should use a single counter instead of running 100 instances. See setInterval() Commented Sep 25, 2018 at 11:39
  • i >= 5 ? 30000 + 1000*i : 1000*i Commented Sep 25, 2018 at 11:40
  • i need every 5 times not first 5 times Commented Sep 25, 2018 at 11:42

2 Answers 2

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);
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

what if for synchronous? , because this is intended for the console so I need syncronus sequentially
Just drop the "async"?
1

The simplest way, without promises.

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

5 Comments

Is there a relation between the question and your answer?
@GerardH.Pille what?
After your edit, it's a lot better. But the OP asks for an extra pause of 30 seconds, every 5 iterations. You replace the 1 second pause by the 30 second one, which is not what is asked. Moreover, you never stop, while the OP stops after 100 iterations.
And your code is not even working. You forgot to call sayHai() and even when its called, there is a delay of 30 seconds after the first console.log
Corrected. But sayHai may be called when needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.