How to write efficient JavaScript code with the Event Loop

The Event Loop is one of the most important aspects in JavaScript, knowledge of which allows you to write more efficient code. In this article, we’ll take a look at how the main thread works in JavaScript and how it handles asynchronous functions.

For a long time, I’ve been writing JavaScript code without fully understanding how it works under the hood. Basically, in order to code in JavaScript, you don’t need to know how it works from the inside, but it will make your code better and allow you to look at some things in the language from a different angle.

All JavaScript code is executed in a single thread, which means that only one thing can be processed at a time. On the one hand, this is a useful limitation, since it allows us not to think about the specifics of working with parallelism. On the other hand, we must constantly monitor the code and make sure that synchronous operations (infinite loops, requesting data over the network) do not block our thread.

In most browsers, each tab has its own event loop, this allows you to isolate the tabs from each other, and if one hangs, the others will continue to work. Otherwise, one hung operation could break the entire browser across all tabs.

In fact, the environment can simultaneously manage a large number of “event loops” to process API requests. WebWorkers also have their own event loop.

A JavaScript developer must be aware that his code is always executed in the same event loop, and be careful not to block it.

Blocking Event Loop

Any code that takes a long time to execute before returning control to the main thread will block the execution of any JavaScript code on the page. This also blocks the user interface, and the user cannot interact with it (click, scroll the page, etc.).

Almost all I / O operations in JavaScript are non-blocking – network requests, file system operations in Node.js, etc. The exception is blocking operations, which is why callbacks are so popular in JavaScript, and more recently all they are starting to use Promise and async / await more often.