JavaScript Explained: The Event Loop

To make complete sense of this article, please make sure to get yourselves familiarized about call stack and execution context: https://medium.com/@srikanthbandaru/javascript-what-is-execution-context-call-stack-9e28e15f07ad

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.

Let’s suppose the Javascript engine is running some function foo(), and in the meantime, a user clicks on a button on the webpage. A KeyPress event would be fired and since Javascript engine is busy executing 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,

// Hello!
// 3
// 1
// 2

Under the hood

First, console.log(“Hello!”); is executed and as a result, Hello! is logged on to the console. Now, it looks atfetch. But, fetch is a Web-API method and JavaScript itself doesn’t know what to do with it. So, it hands it off to the Web API’s. The same goes for the setTimeout. So, it is also handed off the Web API’s for execution.

Now, after completing execution of the web API's, fetch() and 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.

That’s it! That is what basically event loop does.

Peace!!

Full Stack #JavaScript Developer — https://bsrikanth.com

Full Stack #JavaScript Developer — https://bsrikanth.com