Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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...");
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
177 views
Welcome To Ask or Share your Answers For Others

1 Answer

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...");
 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...