To make complete sense of this article, please make sure to get yourselves familiarized about
call stack and
Now, how can a language be both single-threaded but asynchronous at the same time? The answer is because of the Event Loop and the associated Event Queue.
foo(), this new click event would be queued in the Event Queue (also called the callback Queue).
Let’s look at the below code to understand it well.
If you haven’t figured it out already, the output of the above code in most machines with a fast network is,
Under the hood
console.log(“Hello!”); is executed and as a result,
Hello! is logged on to the console. Now, it looks at
setTimeout. So, it is also handed off the Web API’s for execution.
Now, after completing execution of the web API's,
setTimeout() are sent to the callback queue.
If the call stack is empty, the Event Loop checks for the next message in the queue and sends it to the call stack.
Basic job of the Event Loop is to look both at the call stack and the task queue, pushing the first thing on the queue to the stack when it sees stack as empty.
That’s it! That is what basically event loop does.