0

I want to stop the endless while loop after 2 seconds, so I tried with the below code but it's still running endlessly and setTimeout is not getting triggered. Can someone please suggest, what changes should I do in this code ?

let a = true

setTimeout(()=>{
    a = false
},2000)

while(a){
    console.log('While Loop');
}
1
  • Just got a perfect solution for the above problem Sharing the solution below let a = true setTimeout(()=>{ a = false },2000) let prevTime = Date.now(); while(a){ console.log('While Loop'); if(Date.now() - prevTime > 2000){ a = false; console.log('Loop finished') } } Commented Dec 3, 2022 at 11:48

1 Answer 1

0

That's because your task never finishes so that micro task never gets to run. Micro tasks run when a (any) task has been completed.

You see that is quite an antipattern. You also don't have any kind of throttling there. Even if it wasn't flawed due to the micro tasks stuff, it would be extremely CPU intensive and print hundred of thousands of times per second.

There is a couple ways though, setinterval or requestAnimationFrame come to mind.

Simple example / pseudo code for setInterval. Assuming you have a declared and initialized with true and set it to false at some point like you have shown.

let a = true

setTimeout(()=>{
    a = false
},2000)

let interval = setInterval(() => {
    If (!a) {
        clearInterval(interval)
        return
    }
    console.log("looping")
}, 0)

I recommend watching this https://youtu.be/cCOL7MC4Pl0

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the response. But could you please help me with the code that would stop printing "while loop" in exactly 2 seconds.
Just change the while loop for that setInterval. Keep your timeout. I have added your timeout to my snippet. I'm on phone so there may be typos or small inaccuracies. You should get it working though.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.