JavaScript Event Loop Simplified
Tags: javascript, webdev, todayilearned
Published: 2023-03-04 09:22:16

We will examine one super important topic in this installment - **event loops**. This is something every JavaScript developer should tackle as soon as possible in their career. Understanding Event Loop can save you a **lot** of time. 

---

**Promises** and **external APIs** have made our programs _faster_ and _more flexible_. Promises and external APIs have been instrumental in making our programs more efficient. But in this post, we will be focusing on the **event loop**.

JavaScript is a **single-threaded** language, which means that it can only execute one piece of code at a time. In the past, developers had to use various _tricks_ to make JavaScript run faster.

The event loop is a **fundamental feature** in JavaScript. It allows for the **asynchronous execution of code**.

---

## Event Loop Components

To handle many tasks at the same time, we need to _delay the execution_ of code until a specific event or point. The event loop, along with the **call stack** and **task queue**, make this possible. 

### Call Stack and Task Queue

The **call stack** and **task queue** are the two _main components_ of the event loop. The role of the call stack is pretty much to keep track of execution in the _execution context_.

Imagine a call stack looking like a **container**, that holds the names of the **functions** or **methods**. The first method that is getting called is then added to the bottom of the call stack. It will execute right away or wait for other functions, depending on their position in the stack.

A **task queue** is a list of tasks that are waiting for execution by the event loop. Like the call stack, it holds the names of functions in its container.


![Image description of task queue, and the way it operates.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mrgoyd2914qf9h2gc3x7.png)

In the above figure, we can see how the call stack and task queue work together. This will help us understand how the event loop operates. The event loop operates in a _continuous loop_ - it checks the call stack and the task queue.

The system adds code to the call stack and executes it within the execution context as it executes it.

The event loop **evaluates** whether the code is being _blocked_ or _waiting_ for another event. If the code is blocked, it stays on the call stack until the event or blocker is finally resolved. Afterward, the event loop pushes the associated callback function onto the task queue. 

The event loop allows for asynchronous code execution. Checking the call stack and task queue, and running any ready tasks. This makes it possible for JavaScript to handle many tasks at once, instead of one at a time.


![Image description picturing how Call Stack and Task Queue work along forming the event loop.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kicuwt5p3ysgg0aig185.png)

---

### History of Asynchronous Code

To mitigate synchronicity, JavaScript developers used `setTimeout` and `setInterval`. This led to a plethora of complex code and poor performance.

With the release of ES6, JavaScript introduced **promises**. Promises allowed developers to create a placeholder object in the execution thread. That object lets the program continue, without blocking the execution thread. The promise would resolve, and the placeholder object would get the data.

Later, JavaScript introduced **async** and **await**. This allowed developers **to write asynchronous code**, that behaved synchronously. Developers now could evolve from the _hacky_ approach and build more readable applications.

---

### Network Requests Handling

In this example, the event loop will handle the **network request**. We will fetch the data from the various servers. A common example in web development - is loading information from another server and displaying it to the user. 
Let's see how it would look if there was no event loop in the game.


![How network requests work when we are using synchronous code.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0ap4i41lga89teee2sew.png)

The figure above shows the data flow - from `getData()` up to the final result. Let's pretend that we want to fetch socials data for a specific user with the `getData()` function.

Assume that `getData()` holds `getTweets()`, `getInstas()`, `getLinkedins()`, `getFacebooks()`. This means that we need 4 requests to different servers.

Let's say that for each request it takes `400ms` to fetch, and 1ms to populate. This means `1604ms` in the best-case scenario to finish the program. That way of handling data is **unacceptable**.

---

Imagine waiting `1604ms` to get the data and then continuing with the rest of the program. How would this affect the end user?

This is the moment where the event loop comes in handy. What the event loop will do, alongside the promises, will continue to execute. Upon triggering such a function, it creates a **placeholder object** in the **global memory**. 

After the event loop does its job, it will return the data as the promise _resolves_. The rest of the application will continue to execute. The event loop will check the call stack and task queue, filling in the data needed in the global memory. Returning the result to the user.


![Image description of how event loop works alongside promises, making programs faster in execution time.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q3c61q6y9bt3bn87lxg9.png)

To summarize, the event loop helps your app by taking the heavy load and letting the application do the rest. The program continues to execute in the global context, checking the event loop for any data. 

---

## Conclusion

Without an event loop, JavaScript would be a **synchronous** (it's still is, but wouldn't be able to act asynchronously) language. JavaScript would execute code line-by-line, and specific events would block the code execution. 

This would make the application less responsive, and less efficient. Slower loading times irritate and make users appreciate your app less. It also means that the application is less responsive and less efficient.

Consider the event loop as an **essential feature** that enables **asynchronous code execution**. Understanding the event loop can help you as a developer to write better code. As we have seen the network request, takes quite a heavy lifting for us.

**Promises** and **external APIs** in ES6 improved the performance of JavaScript applications. Understanding of event loop is an important concept for you, a JavaScript developer. I hope this will help you a better understanding of it.