I read Nodejs Event Loop and "Event Loop Explained" and Don't Block the Event Loop
I don't think there is a for/while forever loop in nodejs code (js or c++), e.g. as here explains libev event loop http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod#EXAMPLE_PROGRAM
int
main (void)
{
// use the default event loop unless you have special needs
struct ev_loop *loop = EV_DEFAULT;
// init
// now wait for events to arrive
ev_run (loop, 0);
// break was called, so exit
return 0;
}
So how does nodejs event loop run forever or maybe there is indeed a for/while forever loop, as https://en.wikipedia.org/wiki/Event_loop pseudo code shows ?
I searched all SO sites and find Is an event loop just a for/while loop with optimized polling?. There are different opinions there, e.g. Bryan Oakley's answer said yes and other said no.
But my question is a little bit different from that one. I was wondering without a for/while loop, how does nodejs event loop keeps running?
Why would it use "while true" loop? Even though it's commonly stated that "it's an infinite loop", that doesn't mean it's an actually
whileloop.As you've read in "Event Loop Explained", there are different phases in the event loop cycle. After it's done with the last phase, it basically sleeps itself for some short period of time and starts from the first phase again. It's commonly known that in browsers, using
setTimeout(callback, 0)actually executes in4 or moremilliseconds, meaning there's a gap between the cycles of at least 4ms.I think your biggest misunderstanding here is taking the words too literally. Bryan says "From a conceptual point of view, all event loops are essentially", which doesn't mean there's an actual while loop there. It's way more complex and uses OS internal scheduling (kernel) to wait for some period of time. I'd say a better example (still way way too far from actual implementation) would be: