Skip to main content

Asynchronous Event loop

@serverSerrverlesskiy

Asynchronous

In JavaScript, asynchrony is the main tool that processes requests in parallel with the loading of a web page. Now it is impossible to imagine the Internet, where all requests to the server would be sent with a page reload.

Any data from the server is requested asynchronously: a request is sent (XMLHttpRequest or XHR), and the code does not wait for its return, continuing to execute. When the server responds, the XHR object is notified of this and runs the callback function that was passed to it before sending the request.

If you use the language tools correctly , then the execution of a request, which occurs sequentially and in one thread, does not interfere in any way with the reception of events and the reaction to them - a person calmly works with the interface, not noticing lags, crashes and freezes.

Event loop

Queue

The JavaScript Event loop is an asynchronous call manager.

To make this tricky process work smoothly, JavaScript implements a mechanism to control the sequence of code execution. Since it is a single-threaded language , it became necessary to "wedge" into the current execution context. This mechanism is called an event loop.

From English, loop translates as" loop ", which perfectly reflects the meaning: we are dealing with a loopback queue.

Event loop regulates the sequence of execution of contexts - the stack. It is generated when an event was triggered or a function was called. The response to the event is placed in the execution queue, in the event loop, which sequentially, with each loop, executes the code that gets into it. In this case, the function bound to the event is called next after the current execution context.

In JavaScript, synchronous and asynchronous execution queues are constantly running. Synchronous - stack - forms a queue and forwards to asynchronous - event loop - function calls⚙️ that will be executed after the currently scheduled executable context.

For data to be in a consistent state, each function must be completed. This is due to the single-threading of JavaScript and some other features, such as closures characteristic of functional "languages" of programming. Therefore, a single thread is represented as a queue of execution contexts, in which functions that have passed through the event loop are "wedged".

Description

JavaScript is a single-threaded language: only one task can run at a time. This is usually no big deal, but now imagine you are running a task that takes 30 seconds ... Yes. During this task, we wait 30 seconds before anything else can happen (by default, JavaScript runs on the main browser thread, so the entire UI will wait) It's 2021 now, no one wants a slow site that is dumb.

Fortunately, the browser provides us with some functionality that JavaScript itself does not provide: the Web API. Which includes DOM API, setTimeout, HTTP requests, and so on. This can help us create asynchronous non-blocking behavior .

When we call a function, it is added to the call stack. The call stack is part of the JS engine, it is browser independent. This is a classic view of the stack, i.e. first in, last out. When a function returns, it is popped off the stack.

function great() {
return 'Hello'
}

function respond() {
return setTimeout(() => alert('Hey!'), 1000)
}

great()
respond()

stack

The respond function returns the setTimeout function. SetTimeout is provided to us through the Web-API: it allows us to divide tasks without blocking the main thread. The Callback function we passed to the setTimeout function, the () => {return 'Hey'} lambda function is added to the Web-API. Meanwhile, setTimeout and responde are popped from the stack and return their values.

timer

In Web-API, the timer runs until the second argument we passed to it waits for 1000ms. The callback is not immediately added to the call stack, but passed to something called a queue.

queue

This can be confusing: it does not mean that the callback function is added to the call stack (thus returning a value) after 1000ms! It just gets added to the queue after 1000ms. But in this queue, the function must wait until it is its turn.

Now this is the part we've all been waiting for ... Time for the event loop to do one thing: connect the queue to the call stack! If the call stack is empty, that is, if all previously called functions returned their values ​​and were popped from the stack, the first item in the queue is added to the call stack. In this case, no other functions were called, which means that the call stack was empty by the time the callback function was the first item in the queue.

qtoc

callback is pushed onto the call stack, called and returned, and popped off the stack.

result

It's fun to watch, but you can't fully grasp a topic without working on it over and over again. Try to figure out what appears in the console if we run the following:

const foo = () => console.log('First')
const bar = () => setTimeout(() => console.log('Second'), 500)
const baz = () => console.log('Third')

bar()
foo()
baz()

Let's see what happens when we run this code in a browser:

br

We call bar, which returns the setTimeout function. The Callback that we passed to setTimeout is added to the Web API, the setTimeout and bar functions are popped from the call stack.

The timer starts, meanwhile foo is called and logs First. foo returns undefined, baz is called and callback is added to the queue baz logs Third. The event loop sees that the callstack is empty after baz returns, after which the callback is added to the call stack. Callback logs Second.

Hope this makes you feel more confident with the event loop!

Don't worry if this still seems confusing, the most important thing is to understand where certain bugs or specific behavior might come from.

EnglishMoji!

Problems?

Problem

Write to Discord chat.

Questions:

Question

Asynchrony is:

  1. A tool that displays the execution context of a function from a synchronous stream
  2. A tool that executes code line by line
  3. A tool that processes requests in parallel with the loading of web pages

Asynchronous Call Manager:

  1. stack
  2. Event loop
  3. JavaScript

Function calls are placed in:

  1. Stack
  2. A bunch of
  3. Loop

Tool that executes code with a millisecond delay:

  1. delay
  2. heap
  3. setTimeout

In order to understand how much you learned this lesson, take the test in the mobile application of our school on this topic or in our telegram bot.

EnglishMoji!

  1. Explaining how EventLoop works in JavaScript
  2. How to manage event loop in JavaScript
  3. Javascript reference
  4. Article: Explaining Event Loop in Javascript Using Rendering
  5. Article: JavaScript Visualized: Promises & Async / Await

Contributors ✨

Thanks goes to these wonderful people (emoji key):


AlisaNasibullina


Dmitriy Vasilev

💵

Resoner2005

🐛 🎨