Code

Managing the Event Loop in JavaScript - 1

Managing the Event Loop in JavaScript - 1 / Skillbox Media

Master the profession of a front-end developer with an emphasis on artificial intelligence

Learn more

Understanding the mechanisms of the event loop is an important step on the path to professional growth for a mid-level developer.

Alexander Kuzmin, an experienced programmer with more than ten years of experience in the frontend field and the head of the client solutions development department at IT-Park, will now talk about event loops. Let's hand over to our expert.

Understanding Asynchronous Processes in JavaScript

Each programming language offers unique methods for implementing parallel computing. For example, in languages ​​such as C++, this problem is solved by creating a separate thread or even a process that can be executed on another computing system.

Alexander Kuzmin

Chief Programmer and Director of the Client Development Department at IT-Park

When there is a need to transfer a task to a thread, for example: “perform calculations and save the result in When we say "database, and I'll come back for it later," we're dealing with asynchronous processes.

This means that the code that initiated execution doesn't stop waiting for it to complete, but continues its work. However, if we need to wait for the result, many modern programming languages ​​offer the async and await constructs, which allow us to synchronize code execution.

Async is a key feature of JavaScript. In the pre-Node.JS era, it was essentially the only language used for client-side scripting on the web (although Internet Explorer supported VB Script, its use was extremely rare). Today, it's hard to imagine a web in which every request to the server required a page reload. Instead, we see the rise of single-page applications, where URL resolution and content rendering occurs on the client.

Requests to the server are made asynchronously: a request is initiated (via XMLHttpRequest or XHR), and the program continues executing without waiting for a response. Once the server provides the data, the XHR object receives a signal and invokes the callback function specified before the request was sent.

When it needs to wait for a request, JavaScript stops processing any events, which can cause the page to freeze. To ensure a smooth user experience, requests are executed outside the main execution context. Operations that require waiting for a result before continuing code execution are called blocking. Details about these operations will be discussed in the second part of the article.

The essence lies in the structure of the language.

With proper use of language tools, sequential execution of code in a single thread does not interfere with the processing of events and responses to them. The user can comfortably interact with the interface without experiencing delays, crashes, or freezes.

The Event Loop in JavaScript: Managing Asynchronous Processes

In order for this complex process to function efficiently, JavaScript has developed a mechanism that manages the order of code execution. Given that the language is single-threaded, there was a need for integration into the current execution context. This mechanism is called the event loop.

The word «loop» In English, the word "loop" translates as "loop," which perfectly illustrates its meaning: it's a closed loop queue.

The event loop manages the order of execution contexts by creating a stack. It's formed when an event occurs or a function is called. The response to an event is added to the execution queue within the event loop, which sequentially processes code with each new cycle. In this process, the function associated with the event is called immediately after the current execution context ends.

In JavaScript, there is an interaction between synchronous and asynchronous execution queues, which work in close conjunction with each other. The synchronous queue, represented by the stack, creates a sequence of calls and passes them to the asynchronous queue, known as the event loop. The latter queue is responsible for executing functions scheduled for execution after the current execution context ends.

To ensure data consistency, each function must complete completely. This is due to JavaScript's single-threaded nature, as well as a number of other characteristics, including closures, typical of functional programming languages. In this regard, a single thread is implemented in the format of an execution context queue, where the interpolation of functions processed in the event loop occurs.

Event loop diagram. At each stage, one of its queues is checked. Despite the names, setImmediate is executed inside the loop every iteration (tick), and nextTick is called at the moment of execution - between the stages of the loop.

In JavaScript, there is such a thing as a "function context". However, there is an alternative term - "execution context". This context is the body of the function, which contains all the variables and nested functions, and it is called "scope" in English. It is very important to distinguish between these terms, since they denote completely different concepts.

The Process of Creating an Execution Context

JavaScript is an interpreted language, which means that the code is processed by an interpreter, which executes it line by line. However, this process has its own peculiarities.

When a script begins executing in the interpreter, a global context and global scope are created. As part of this process, a variable object, known as a Variable Object, or VO, is formed.

It is created from variables representing function declarations, as well as the attributes of these functions, following a specific principle. The interpreter parses the code and detects all relevant declarations:

  • variables defined with the var keyword (or with const and let in ES6 and later);
  • functions created with the function keyword, without specifying an assignment.

This creates a Variable Object (VO) within the current execution context. Next, the VO is extracted from the outer scope, and the previously created VO is added to it. Finally, it is populated with the function parameters and their values ​​at runtime.

It is important to note that where functions are defined does not matter. Variables, like functions, can be declared anywhere in a program.

Consider the following script:

The voiceover for this script is created as follows:

After this, the script will begin executing according to the following plan:

Let's modify the script by inserting a function call using setTimeout set to zero delay.

At first glance, it might seem that the func function will execute instantly and without any delay. However, this is far from the truth. In fact, the following events will occur:

The relationship between front-end development and artificial intelligence

Thanks to the work of front-end developers, we are able to like and leave comments, add products to the cart and easily navigate online maps. In this course, you will learn how to create interfaces for web services using programming languages ​​and various technologies. You will be able to develop applications such as task schedulers, instant messengers, and online stores.

Find out more