Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

What is event loop in JavaScript

Understanding Event Loop in JavaScript

Before we dive into the heart of the topic, let's set the stage by imagining a busy restaurant during rush hour. The kitchen staff are your web browser's Web APIs, the waiter taking the orders is the Call Stack, and the customers are the tasks or functions waiting to be executed. Now, imagine there's a single waiter (JavaScript is single threaded, meaning it can only do one thing at a time), and they have to handle multiple tables. This is where the Event Loop comes in. It's like the restaurant manager who organizes the waiter's tasks in a way that keeps the restaurant running smoothly.

What is an Event Loop?

In simplest terms, an Event Loop is a mechanism that checks if there's any task that needs to be executed. If there is, it's taken from the queue and sent to be executed.

Let's break down this concept with the help of a code example.

console.log('Hello');
setTimeout(function() {
  console.log('JavaScript');
}, 0);
console.log('World');

In the above code snippet, even though the setTimeout function has a delay of 0 milliseconds, the output will be:

Hello
World
JavaScript

This happens because JavaScript doesn't execute your code top-to-bottom as you might expect. It has an Event Loop that helps manage when each piece of your code should run.

The Call Stack and Web APIs

The Call Stack is a stack of frames that keeps track of the function calls in your code. When you call a function, a new frame is added to the stack. When a function returns, its frame is removed from the stack.

In our example, when the JavaScript engine sees the console.log('Hello') function call, it puts this function onto the Call Stack and executes it. After execution, it is removed from the stack.

Next, it sees setTimeout(function() { console.log('JavaScript'); }, 0);. setTimeout is a Web API provided by the browser. JavaScript engine doesn't handle the timer itself, but hands it off to the Web APIs. Once the timer expires, the callback function is put into a Task Queue.

Finally, it executes console.log('World'), adding and then removing it from the Call Stack.

The Task Queue

The Task Queue, also known as the Callback Queue, is a list of all the tasks that are ready to be executed but are waiting for the Call Stack to be empty. They have already been handled by the Web APIs and are ready to be executed in the order they were called.

Coming back to our code, after the timer in the setTimeout function expires, the callback function is added to the Task Queue.

The Event Loop

The Event Loop has one simple job: checking if the Call Stack is empty. If it is, it takes the first task from the Task Queue and pushes it onto the Call Stack, which immediately executes it.

In our example, once the Call Stack is empty, the Event Loop takes the callback function from the Task Queue and pushes it onto the Call Stack.

Why is this Important?

Understanding the Event Loop is crucial because it affects the performance of your code. It helps you understand why your JavaScript code might not run in the order you expect and how you can handle tasks asynchronously, improving the performance of your application.

Conclusion

In the grand restaurant of JavaScript, the Event Loop serves as the orchestrator, ensuring every customer gets their order in the most efficient way possible. It's like the conductor of an orchestra, directing each musician when to play their part. So next time when you're writing code, remember to tip your hat to the Event Loop, the unsung hero that keeps your code running smoothly. Learning about the Event Loop might seem like a daunting task at first, but once you understand it, it'll be an invaluable tool in your JavaScript toolkit. Happy coding!