-1

Can't explain nodejs behavior. I have code:

while (true) {
  setTimeout(() => console.log(1), 0)
}

And this script just hanging...

How come? I've been thinking setTimeout is non-blocking and asynchronous, and nodejs use timers event loop phase for scheduling setTimeout callbacks... but it seems like event loop blocked...

4
  • So you have an infinite loop that executes console.log(1) "outside" of that loop... what are you expecting here? I'm not even sure the console.log will get into the current thread... Commented Sep 14, 2017 at 21:45
  • Check out this amazing answer of a question a asked a while ago about the same topic. Commented Sep 14, 2017 at 21:51
  • Hey, @KevinB! Thank you for providing link to question which I've duplicated, just can't understand why I didn't manage to find it by my own... I've spent some time to find such questions... Anyway, thx! Commented Sep 14, 2017 at 21:55
  • searching is an acquired skill, you'll get better at it with time. Just takes practice. I also suggest using google directly, rather than SO's search. Commented Sep 14, 2017 at 21:55

1 Answer 1

7

Your while loop is infinite. It will just keep setting timeouts and never exiting the loop. Since JavaScript is single-threaded, the code for the timeouts won't run until the current code is finished, and since the while loop never finishes, the timeouts don't run.

If you want to spam the console with the number 1 using timeouts, which it looks like you are trying to do, you would have to set the next timeout in the current timeout's callback:

function timeoutFunc() {
  console.log(1);
  setTimeout(timeoutFunc, 0);
}

timeoutFunc();

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.