Some relevant facts for Javascript running in a browser or nodejs environment:
- Javascript runs your Javascript in a single thread
- Javascript is event driven
- Functions like
setTimeout()
trigger their callback to be called only via the event loop
- A
while
loop (that does not contain an await
) is a blocking structure in Javascript and nothing else can run until that while
loop finishes and returns control back to the event loop.
So, given all that, your while
loop just runs forever. It hogs the interpreter and because it's hogging the interpreter and nothing else can run, the value of i
never changes and thus your while
loop can never complete and return control back to the event loop. The setTimeout()
callback is sitting there waiting to run in the event loop, but never gets to run because the while
loop never returns control back to the event loop. The while
loop just sits there and spins forever since no code inside the while
loop ever causes the value of i
to change.
The basic concept in single threaded, event driven code is that the interpreter runs a piece of Javascript code until it returns. When it returns the interpreter goes back to the event loop to see what else is waiting to run, grabs the next event, calls its callback and similarly waits until it returns before it can then run the next event.
Events like timers are queued and cannot execute their callback until control is returned back to the event loop and until they get their turn in the event loop (as other things might run before them).