JavaScript Explained: The Event Loop

Srikanth Bandaru
Jan 20 · 2 min read

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

JavaScript is a single-threaded, non-blocking, asynchronous, concurrent language.

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.

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.

Peace!!

Srikanth Bandaru

Written by

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

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade