Home > Web Front-end > JS Tutorial > Asynchronous Operations in JavaScript: The Event Loop

Asynchronous Operations in JavaScript: The Event Loop

Barbara Streisand
Release: 2024-10-05 08:18:02
Original
574 people have browsed it

Introduction
JavaScript is Synchronous by Default
Synchronous vs Asynchronous Operations
The Event Loop
How it Works
Importance of the Event Loop
Conclusion


Introduction

Picture this: you just developed a web application that has to fetch data from a server, update the user interface, and respond to all of the user actions in real-time, but you’re worried about whether your code will be able to juggle these tasks efficiently. Well, no need to worry, this is where the event loop comes in.

In this article, I’ll go over how the event loop works, the differences between synchronous and asynchronous operations in JavaScript, and the importance of the event loop as a necessary non-blocking architecture.

Javascript is Synchronous by Default

By default, Javascript is synchronous and code is read sequentially in order from top to bottom. Since JS is single-threaded, each task must wait for the completion of the previous one, before proceeding to the next. What this means is that each line of code is processed, one at a time, and only one operation/function is executed at any given moment.

Asynchronous Operations in JavaScript: The Event Loop

In JavaScript, there is no way to run multiple pieces of code in parallel and any attempt to do parallelism in a language that is synchronous and single-threaded at its core is ambitious. Understanding the synchronous nature of JavaScript will help you realize how web applications respond to user interactions and handle tasks.


function greet(name) {
    return `Hello, ${name}!`;
}

const greeting = greet("Deb");
console.log(greeting);                                                 


Copy after login

In this example, Javascript executes the code in the order it’s written. The ‘greet’ function is called with the argument ‘Deb’. The function then returns a greeting string which is then logged to the console.

Output:


Hello, Deb!


Copy after login

Each line waits for the previous line to finish before executing. Therefore, the function must be completed before the result can be assigned to ‘greeting’.

Synchronous vs Asynchronous Operations

Asynchronous Operations in JavaScript: The Event Loop

Before getting into what the event loop is, I’ll touch a little bit on what asynchronous operations are and the differences between synchronous and asynchronous operations in JavaScript. Asynchronous operations are the activities that run independently of a program flow.

As stated earlier, Javascript is synchronous by default and synchronous code creates a blocking behavior where each task/function must finish before the next one starts.

On the other hand, asynchronous operations do not block the execution of subsequent operations and allows javascript to attend to other tasks while waiting for the completion of that particular asynchronous task. Simply put, if you declare a function as asynchronous (async), it means the function has code that will require time to complete, and such a function will be deferred while the synchronous code runs first.

Since there’s no blocking, the next synchronous code can be executed without finishing the previous async one and any async code that is ready to execute will be queued in the event queue.


// Synchronous code
console.log("Step 1");
console.log("Step 2");


Copy after login

Remember synchronous code is executed line-by-line. Here, JavaScript executes the statements in the order they are written.

Output:


Step 1
Step 2


Copy after login

On the other hand, asynchronous code allows JavaScript to continue executing while waiting for an operation to complete.


// Asynchronous code
console.log("1st Function");

setTimeout{function(){ // WEB API
  console.log("2nd Function");
},2000);

console.log("3rd Function");


Copy after login

Output:


1st Function
3rd Function
2nd Function


Copy after login

since the first and third functions are synchronous, they get executed first while the second function gets removed from the call stack and is handled by the web API. The web API asynchronously orders it to wait for 2000ms before being put into the event queue, which will thereafter be placed back into the empty call stack by the event loop and finally executed.

The Event Loop

In its simplest definition, the event loop is a way of synchronously processing asynchronous events.

In a more elaborate definition, the event loop is a continually running code loop in the Javascript runtime that allows for asynchronous operations to be executed when needed. This means it allows for JavaScript’s limiting design to handle many tasks efficiently.

It spins and stays in your code background until it has specific JavaScript tasks to run. For example, clicking a button that has code associated with it from a click event handler, or when you load an external file, in cases like these, the event loop remains in the insides of the javascript runtime to execute any javascript code when needed.

这一切意味着,尽管 JavaScript 是单线程的,但事件循环使 JavaScript 看起来能够通过将事物卸载到 API 并在可以时处理传入的事件来异步运行事物。

在解释事件循环如何工作之前,您需要了解 JavaScript 运行时中的一些特定概念:

  • 调用堆栈:调用堆栈跟踪调用了哪些函数以及以什么顺序执行它们。它按顺序执行同步代码。

  • Web API:这些是处理异步任务的工具。

  • 回调:这是一个作为参数传递到另一个函数的函数。它有助于执行代码以响应事件。

  • 事件/回调队列:一旦调用堆栈清除,它会保存等待执行的任务。

它是如何运作的

调用堆栈运行同步代码,直到为空。当异步代码添加到调用堆栈时,它会被传输到 API,然后 API 在发送到事件队列之前处理任务。

Asynchronous Operations in JavaScript: The Event Loop

API 完成的回调/函数会添加到事件队列中,事件循环会不断地在事件队列中查找,看看是否有 javascript 需要执行的新事件/任务。

请注意,在调用堆栈为空之前,JavaScript 无法对事件执行操作。因此,一旦调用堆栈为空,事件循环就会从队列中抓取事件并将其放入调用堆栈中,以便像其他常规函数一样执行。

事件循环的重要性

  • 它可以让您的代码在后台执行任务时保持响应。

  • 它通过监控调用堆栈和回调队列来帮助您有效地管理任务。

  • 它为 JavaScript 提供了一种执行非阻塞操作的解决方法,可以同时处理多个任务。

  • 它可以防止你的程序进入回调地狱。当多个回调相互嵌套时,会发生回调地狱,导致代码难以阅读或维护。

结论

事件循环的行为决定了应用程序中的代码何时运行。您对事件循环的使用和需求了解得越多,您就越能理解代码运行的原因。

祝好朋友编码快乐!

The above is the detailed content of Asynchronous Operations in JavaScript: The Event Loop. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template