-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...

cn007b
  • 16,596
  • 7
  • 59
  • 74
  • 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... – Dekel Sep 14 '17 at 21:45
  • Check out [**this amazing answer**](https://stackoverflow.com/a/41814108/6647153) of a question a asked a while ago about the same topic. – ibrahim mahrir Sep 14 '17 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! – cn007b Sep 14 '17 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. – Kevin B Sep 14 '17 at 21:55

1 Answers1

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();
Mogzol
  • 1,405
  • 1
  • 12
  • 18