0
for (i=0;i<5;i++){
setTimeout(bye,2000)}

console.log("asda")

function bye(){
  console.log("gudbye")
}

I want the program to log bye once evey 2 second,but this works just for the fist log, so i get instantly 5 time "gudbye" in 2 seconds

1 Answers1

0

Change your code to:

setInterval(bye,2000)

function bye(){
  console.log("gudbye")
}

setInterval will run your function every 2 seconds, instead of running just one time after 2000 seconds per call.

but if you only want it to be called 5 times you can try the recursive aproach:

bye(1)
function bye(callCount){
  console.log("gudbye")
  if(callCount < 5){
      setTimeout(() => bye(callCount+1), 2000);
  }
}
Otacílio Maia
  • 311
  • 1
  • 8
  • But it also never stops. Whereas original poster wanted to run 5 times. – Marc Nov 22 '20 at 02:08
  • I'm not sure if the original poster only wants 5 times, but if its the case, it can be changes to something like: bye(0) function bye(callCount){ console.log("gudbye") if(callCount < 5){ setTimeout(() => bye(callCount+1), 2000); } } – Otacílio Maia Nov 22 '20 at 02:12