What the heck is an Event Loop? Event Loop in Javascript Explained

Photo by Chris Ried on Unsplash

What the heck is an Event Loop? Event Loop in Javascript Explained

Learn about the inner working of the browser engine in 5 minutes

If you are working with any fairly advanced applications In Javascript, you would have to work with both synchronous and asynchronous code. Understanding how the Javascript engine executes these different parts of the code is essential to building better applications.

First, What is an asynchronous code anyway?

Asynchronous Code in JS

Javascript is a single-threaded language. Which means any code written will execute on the main thread. What if we have a setTimeout() call that executes a function after 1000ms? It wouldn't be a good UX if we blocked any user actions until the function executes. So, the tasks from the setTimeout() and other code which may take some time to execute (Network Requests, etc.,) are executed "in parallel".

While...Event Loop?

How the Event Loop works in the Chrome browser | by Roman Melnik |  JavaScript in Plain English

The Event Loop is how the Browser Engine decides which action will be executed next. The Event Loop initially executes all the synchronous tasks on the stack until the stack is empty.

Now, we have two different types of asynchronous code, one invoked with callbacks and another involving promises.

So the functions that use callbacks will be put into the tasks queue. On every single cycle of the Event loop, one task from the tasks queue is taken and executed. This is true even if multiple elements are present.

When promises are used, the functions are inserted into a separate queue called the Microtasks queue.

On every iteration of the Event Loop, after synchronous code is executed, the Microtasks queue is executed until the queue is empty.

Browser Animations

The final part of the Event Loop that we need to discuss involves the Rendering process of the Browser.

The Browser provides us with the requestAnimationFrame() function, that allows us to update animations before the next repaint. You can read more about it here.

The callbacks related to requestAnimationFrame() are the third type of queues in the Event Loop. For every iteration, the synchronous code is first executed, followed by tasks from the Microtask queue. After completion, it goes around the completes the animation callbacks, and then iterates over the event loop again. If there are no synchronous code, then the task queue functions are executed.

The primary thing to note about the Animation Callback queue is, all items in the queue are executed, except ones that were added in the current execution context. These items will be executed on the next run of the Event Loop.

Want to Know More?

This article is just my 5-minute summary of the detailed Explanation from Jake Archibald on the topic. If you would like to know more, watch this video.