2

Hey folks I'm having some trouble to solve an async issue in Node.js

let isDone = false;
setTimeOut(() => { isDone = true }, 1000)

let i = 0;
while(!isDone) {
 console.log(i++)
}

The thing is, isDone eventually becomes true, but the while keeps forever, why?

2
  • 5
    There is no opportunity for the setTimeout function to execute because the thread is blocked with the while loop. Commented May 14, 2019 at 18:40
  • Guess I miss some computer architecture class, thanks @James Commented May 14, 2019 at 18:42

1 Answer 1

3

Firstly, setTimeout, lowercase o.

Secondly, as James@ comment said, this is a blocking issue caused by the fact that JS is single threaded and won't resume async code (promises, timeouts, intervals) until it has a free execution cycle. To get around this, you could wrap the later part of your snippet (the while loop) inside an interval. This will give the JS engine to chance to check for ready async code at each iteration of the while

let isDone = false;
setTimeout(() => {
  isDone = true;
}, 1000);

let i = 0;
let interval = setInterval(() => {
  if (isDone)
    clearInterval(interval);
  else
    console.log(i++);
}, 0);

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

Comments

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.