Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Leave a loop after 2 seonds

Tags:

javascript

I would like to repeat a text for 2 seconds in a while loop. How do I break the loop after 2 seconds?

This is what I have tried so far but it doesn't work:

var repeat = true;
setTimeout(function() { var repeat = false }, 2000)
while(repeat) {
    console.log("Let's repeat for 2 seconds...");
}
like image 984
Reza Saadati Avatar asked Sep 15 '25 09:09

Reza Saadati


1 Answers

Additionaly to the other answer you could just check the time instead:

 const start = +new Date;

  while(+new Date < start + 2000) {
     console.log("Let's repeat for 2 seconds...");
 }
like image 97
Jonas Wilms Avatar answered Sep 17 '25 22:09

Jonas Wilms



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!