I saw a pathological code snippet written in LinkedIn so while the example itself doesn't matter, I'd like to understand why the code behaves this way
let run = true;
setTimeout(()=>{run=false;},0);
while (run) {console.log("running...");}
Which prints "running..." repeatedly since run=false
is never executed.
But why is this case? The time to execute is set to 0 seconds so why is it not ran as soon as the line is interpreted?
Answers talked about yielding the call stack, the event never running because the current task is still running, etc.. But I'm not familiar with how this actually works.
If I had to guess, my explanation would be setTimeout is an async function that is auto-awaited the next time the current execution polls the other threads but for some reason the while loop never allows this polling to happen
But idk if that's right or if I'm speaking nonsense