The requests that Express serves all go through the event queue just like the setTimeout()
so they share the same event queue and can be interleaved just fine.
So, when an incoming request arrives on the Express server, some lower level TCP code inserts that incoming connection into the event queue. The next time Express finishes executing something, the nodejs interpreter goes back to the event queue and grabs the next event. That could be the next incoming request, it could be some intermediate asynchronous operation in servicing a request (such as a database query finishing) or it could be your setTimeout()
.
Events are generally served FIFO (first-in-first-out), though there are some priorities among different types of events that can effect ordering details when there are multiple different types of events in the queue waiting to run.
The Express app (I'm assuming) is always running because it's always listening for requests so I thought that since the program never finishes, the setTimeout would never run. But the setTimeout ran just fine and on time.
"Always running", in this case, just means that it is ready and waiting for an incoming request. Other things in the event queue (like a timer) are able to run just fine whenever the JS interpreter returns back to the event loop for the next event.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…