I've been reading some NodeJs articles in order to understand its async nature during which I found this and really liked it Node.js, Doctor’s Offices and Fast Food Restaurants – Understanding Event-driven Programming
There is a thing called EventLoop
that is FIFO based queue. They say when an async function gets hit, it gets put to EventLoop and will continue to get executed over there.
I am little confused here. For example it is said here:
In actuality, async functions like setTimeout and setInterval are pushed onto an queue known as the Event Loop.
and in the same article:
The Event Loop is a queue of callback functions. When an async function executes, the callback function is pushed into the queue. The JavaScript engine doesn't start processing the event loop until the code after an async function has executed.
But it is different than this image:
Let's look at the following example:
console.log("Hello,");
setTimeout(function(){console.log("World");},0);
So from what I understand from those different explanations,
function(){console.log("World");}
part of the setTimeout()
function, that is the callback, will be put in EventLoop. Once the setTimeout
is done, it will execute the EventLoop
as well.setTimeout(function(){console.log("World");},0);
will be put the EventLoop and will get executed...I am confused even more now. It should be something simple but I guess a good but simple explanation would be nice for me for the following questions:
I'm going to attempt to answer, based on MDN's little information regarding Event Loops. Note, this answer is strictly for JavaScript, not specifically for Node.
From the sound of it, the confusion is that your second quote should probably have been written more clearly, such as:
The Event Loop is a queue of callback functions. When an async function executes, the callback function is pushed into the queue. The JavaScript engine doesn't
startcontinue processing the event loop until the code after an async function has executed.
If that's the case, then it's much more consistent. All callbacks, when they fire, are entered into a FIFO queue, and run sequentially. I.e., if one event is firing, the next one won't fire until the first one completes.
The MDN reference I linked to above even includes pseudo-code for the Event Loop:
while(queue.waitForMessage()){
queue.processNextMessage();
}
Timers and intervals are defined as part of DOM in the HTML spec. I couldn't find any direct reference to "Message Loop" in my quick check of that spec.