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,
- First one says
function(){console.log("World");}
part of thesetTimeout()
function, that is the callback, will be put in EventLoop. Once thesetTimeout
is done, it will execute theEventLoop
as well. - The other one says, the whole thing
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:
- Which one of the aforementioned things is true?
- What is EventLoop? An analogy, a real thing with methods, objects, etc?
- If I would like to implement a similar thing as EventLoop from scratch, how would it look like simply? Perhaps some code would be nice to see.