」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 了解 JavaScript 中的非同步程式設計:事件循環初學者指南

了解 JavaScript 中的非同步程式設計:事件循環初學者指南

發佈於2024-11-08
瀏覽:540

Understanding Asynchronous Programming in JavaScript: Beginner

Have you ever wondered why some pieces of JavaScript code seem to run out of order? The key to understanding this is the event loop.

JavaScript's event loop can be tricky to understand, especially when dealing with different types of asynchronous operations. In this article, we'll break down how JavaScript handles synchronous and asynchronous code, microtasks and macrotasks, and why certain things happen in a specific order.

Table of Contents

  1. Synchronous and Asynchronous Codes
    • What are Synchronous Code
    • What are Asynchronous Code
    • Asynchronous Patterns in JavaScript
    • Synchronous vs Asynchronous Code
  2. Microtasks and Macrotasks
    • What are Microtasks
    • What are Macrotasks
    • Microtasks vs Macrotasks
  3. The Event Loop
    • What is the Event Loop
    • How the Event Loop Works
  4. Examples
    • Example 1: Timer with Promises and Event Loop
    • Example 2: Nested Promises and Timers
    • Example 3: Mixed Synchronous and Asynchronous Operations
  5. Conclusion

Synchronous and Asynchronous Codes

JavaScript handles operations in two main ways: synchronous and asynchronous. Understanding the difference between them is key to grasping how JavaScript handles tasks and how to write efficient and non-blocking code.

What are Synchronous Code?

Synchronous code is the default in JavaScript, meaning each line runs one after another in sequence. For example:

console.log("First");
console.log("Second");

This will output:

First
Second

What are Asynchronous Code?

Asynchronous code on the other hand allows certain tasks to run in the background and complete later, without blocking the rest of the code. Functions like setTimeout() or Promise are examples of asynchronous code.

Here's a simple example of asynchronous code using setTimeout():

console.log("First");

setTimeout(() => {
  console.log("Second");
}, 0);

console.log("Third");

This will output:

First
Third
Second

Asynchronous Patterns in JavaScript:

There are a few ways to handle asynchronous operations in JavaScript:

  1. Callbacks: A function passed as an argument to another function, and executed after the first function has completed its task.

Code Sample:

console.log("Start");

function asyncTask(callback) {
  setTimeout(() => {
    console.log("Async task completed");
    callback();
  }, 2000);
}

asyncTask(() => {
  console.log("Task finished");
});

console.log("End");
  1. Promises: A promise represents a future value (or error) that will eventually be returned by the asynchronous function.

Code Sample:

console.log("Start");

const asyncTask = new Promise((resolve) => {
  setTimeout(() => {
    console.log("Async task completed");
    resolve();
  }, 2000);
});

asyncTask.then(() => {
  console.log("Task finished");
});

console.log("End");
  1. Async/Await: Async/await is syntactic sugar built on top of promises, allowing us to write asynchronous code that looks synchronous.

Code Sample:

console.log("Start");

async function asyncTask() {
  await new Promise((resolve) => {
    setTimeout(() => {
      console.log("Async task completed");
      resolve();
    }, 2000);
  });

  console.log("Task finished");
}

asyncTask();

console.log("End");

Synchronous vs Asynchronous Code

To better understand each of these method of execution of javascript and how they differs from each either, here is an elaborate differences across multiple aspect of javascript functions.

Aspect Synchronous Code Asynchronous Code
Execution Order Executes line by line in a sequential manner Allows tasks to run in the background while other code continues to execute
Performance Can lead to performance issues if long-running tasks are involved Better performance for I/O-bound operations; prevents UI freezing in browser environments
Code Complexity Generally simpler and easier to read Can be more complex, especially with nested callbacks (callback hell)
Memory Usage May use more memory if waiting for long operations Generally more memory-efficient for long-running tasks
Scalability Less scalable for applications with many concurrent operations More scalable, especially for applications handling multiple simultaneous operations

This comparison highlights the key differences between synchronous and asynchronous code, helping developers choose the appropriate approach based on their specific use case and performance requirements.


Microtasks and Macrotasks

In JavaScript, microtasks and macrotasks are two types of tasks that are queued and executed in different parts of the event loop, which determines how JavaScript handles asynchronous operations.

Microtasks and macrotasks are both queued and executed in the event loop, but they have different priorities and execution contexts. Microtasks are processed continuously until the microtask queue is empty before moving on to the next task in the macrotask queue. Macrotasks, on the other hand, are executed after the microtask queue has been emptied and before the next event loop cycle starts.

What are Microtasks

Microtasks are tasks that need to be executed after the current operation completes but before the next event loop cycle starts. Microtasks get priority over macrotasks and are processed continuously until the microtask queue is empty before moving on to the next task in the macrotask queue.

Examples of microtasks:

  • Promises (when using .then() or .catch() handlers)
  • MutationObserver callbacks (used to observe changes to the DOM)
  • Some process.nextTick() in Node.js

Code Sample

console.log("Start");

Promise.resolve().then(() => {
  console.log("Microtask");
});

console.log("End");

Output:

Start
End
Microtask

Explanation:

  • The code first logs "Start", which is synchronous.
  • The promise handler (Microtask) is queued as microtask.
  • The "End" is logged (synchronous), then the event loop processes the microtask, logging "Microtask".

What are Macrotasks

Macrotasks are tasks that are executed after the microtask queue has been emptied and before the next event loop cycle starts. These tasks represent operations like I/O or rendering and are usually scheduled after a certain event or after a delay.

Examples of macrotasks:

  • setTimeout()
  • setInterval()
  • setImmediate() (in Node.js)
  • I/O callbacks (file reading/writing)
  • UI rendering tasks (in browsers)

Code Example:

console.log("Start");

setTimeout(() => {
  console.log("Macrotask");
}, 0);

console.log("End");

Output:

Start
End
Macrotask

Explanation:

  • The code first logs "Start", which is synchronous.
  • The setTimeout() (macrotask) is queued.
  • The "End" is logged (synchronous), then the event loop processes the macrotask, logging "Macrotask".

Microtasks vs Macrotasks

Aspect Microtasks Macrotasks
Execution Timing Executed immediately after the current script, before rendering Executed in the next event loop iteration
Queue Priority Higher priority, processed before macrotasks Lower priority, processed after all microtasks are complete
Examples Promises, queueMicrotask(), MutationObserver setTimeout(), setInterval(), I/O operations, UI rendering
Use Case For tasks that need to be executed as soon as possible without yielding to the event loop For tasks that can be deferred or don't require immediate execution

The Event Loop

The event loop is a fundamental concept in JavaScript that enables non-blocking asynchronous operations despite JavaScript being single-threaded. It's responsible for handling asynchronous callbacks and ensuring that JavaScript continues to run smoothly without getting blocked by time-consuming operations.

What is the Event Loop

The event loop is a mechanism that allows JavaScript to handle asynchronous operations efficiently. It continuously checks the call stack and the task queue (or microtask queue) to determine which function should be executed next.

To understand the event loop better, it's important to know how JavaScript works internally. It is important to note that JavaScript is a single-threaded language, meaning it can only do one thing at a time. There's only one call stack, which stores the functions to be executed. This makes synchronous code straightforward, but it poses a problem for tasks like fetching data from a server or setting a timeout, which take time to complete. Without the event loop, JavaScript would be stuck waiting for these tasks, and nothing else would happen.

How the Event Loop Works

1. Call Stack:

The call stack is where the function currently being executed is kept. JavaScript adds and removes functions from the call stack as it processes code.

2. Asynchronous Task Starts:

When an asynchronous task like setTimeout, fetch, or Promise is encountered, JavaScript delegates that task to the browser's Web APIs (like Timer API, Network API, etc.), which handle the task in the background.

3. Task Moves to the Task Queue:

Once the asynchronous task completes (e.g., the timer finishes, or data is received from the server), the callback (the function to handle the result) is moved to the task queue (or microtask queue in the case of promises).

4. Call Stack Finishes Current Execution:

JavaScript continues executing the synchronous code. Once the call stack is empty, the event loop picks up the first task from the task queue (or microtask queue) and places it on the call stack for execution.

5. Repeat:

This process repeats. The event loop ensures that all the asynchronous tasks are handled after the current synchronous tasks are done.

Examples

Now that we a better and clearer understanding of how the event loop works, let's look at some examples to solidify our understanding.

Example 1: Timer with Promises and Event Loop

function exampleOne() {
  console.log("Start");

  setTimeout(() => {
    console.log("Timeout done");
  }, 1000);

  Promise.resolve().then(() => {
    console.log("Resolved");
  });

  console.log("End");
}

exampleOne();

Output:

Start
End
Resolved
Timeout done

Explanation:

  • Step 1: "Start" is printed (synchronous).
  • Step 2: setTimeout schedules the "Timeout done" message after 1 second (macrotask queue).
  • Step 3: A promise is resolved, and the "Resolved" message is pushed to the microtask queue.
  • Step 4: "End" is printed (synchronous).
  • Step 5: The call stack is now empty, so the microtask queue runs first, printing "Resolved".
  • Step 6: After 1 second, the macrotask queue runs, printing "Timeout done".

Example 2: Nested Promises and Timers

function exampleTwo() {
  console.log("Start");

  setTimeout(() => {
    console.log("Timer 1");
  }, 0);

  Promise.resolve().then(() => {
    console.log("Promise 1 Resolved");

    setTimeout(() => {
      console.log("Timer 2");
    }, 0);

    return Promise.resolve().then(() => {
      console.log("Promise 2 Resolved");
    });
  });

  console.log("End");
}

exampleTwo();

Output:

Start
End
Promise 1 Resolved
Promise 2 Resolved
Timer 1
Timer 2

Explanation:

  • Step 1: "Start" is printed (synchronous).
  • Step 2: The first setTimeout schedules "Timer 1" to run (macrotask queue).
  • Step 3: The promise resolves, and its callback is pushed to the microtask queue.
  • Step 4: "End" is printed (synchronous).
  • Step 5: The microtask queue runs first:
    • "Promise 1 Resolved" is printed.
    • "Timer 2" is scheduled (macrotask queue).
    • Another promise is resolved, and "Promise 2 Resolved" is printed.
  • Step 6: The macrotask queue is processed next:
    • "Timer 1" is printed.
    • "Timer 2" is printed last.

Example 3: Mixed Synchronous and Asynchronous Operations

function exampleThree() {
  console.log("Step 1: Synchronous");

  setTimeout(() => {
    console.log("Step 2: Timeout 1");
  }, 0);

  Promise.resolve().then(() => {
    console.log("Step 3: Promise 1 Resolved");

    Promise.resolve().then(() => {
      console.log("Step 4: Promise 2 Resolved");
    });

    setTimeout(() => {
      console.log("Step 5: Timeout 2");
    }, 0);
  });

  setTimeout(() => {
    console.log(
      "Step 6: Immediate (using setTimeout with 0 delay as fallback)"
    );
  }, 0);

  console.log("Step 7: Synchronous End");
}

exampleThree();

Output:

Step 1: Synchronous
Step 7: Synchronous End
Step 3: Promise 1 Resolved
Step 4: Promise 2 Resolved
Step 2: Timeout 1
Step 6: Immediate (using setTimeout with 0 delay as fallback)
Step 5: Timeout 2

Explanation:

  • Step 1: "Step 1: Synchronous" is printed (synchronous).
  • Step 2: The first setTimeout schedules "Step 2: Timeout 1" (macrotask queue).
  • Step 3: A promise resolves, scheduling "Step 3: Promise 1 Resolved" (microtask queue).
  • Step 4: Another synchronous log, "Step 7: Synchronous End", is printed.
  • Step 5: Microtask queue is processed:
    • "Step 3: Promise 1 Resolved" is printed.
    • "Step 4: Promise 2 Resolved" is printed (nested microtask).
  • Step 6: The macrotask queue is processed:
    • "Step 2: Timeout 1" is printed.
    • "Step 6: Immediate (using setTimeout with 0 delay as fallback)" is printed.
    • "Step 5: Timeout 2" is printed last.

Conclusion

In JavaScript, mastering synchronous and asynchronous operations, as well as understanding the event loop and how it handles tasks, is crucial for writing efficient and performant applications.

  • Synchronous functions run in sequence, blocking subsequent code until completion, while asynchronous functions (like setTimeout and promises) allow for non-blocking behavior, enabling efficient multitasking.
  • Microtasks (such as promises) have higher priority than macrotasks (such as setTimeout), meaning that the event loop processes microtasks immediately after the current execution, before moving to the macrotask queue.
  • The event loop is the core mechanism that allows JavaScript to handle asynchronous code by managing the execution order of tasks and ensuring that the call stack is clear before processing the next queue (microtask or macrotask).

The examples provided progressively illustrated the interaction between synchronous code, promises, timers, and the event loop. Understanding these concepts is key to mastering asynchronous programming in JavaScript, ensuring your code runs efficiently and avoids common pitfalls such as race conditions or unexpected execution orders.


Stay Updated and Connected

To ensure you don't miss any part of this series and to connect with me for more in-depth discussions on Software Development (Web, Server, Mobile or Scraping / Automation), push notifications, and other exciting tech topics, follow me on:

  • GitHub
  • Linkedin
  • X (Twitter)

Stay tuned and happy coding ?‍??

版本聲明 本文轉載於:https://dev.to/emmanuelayinde/understanding-asynchronous-programming-in-javascript-synchronous-asynchronous-microtasks-macrotasks-and-the-event-loop-h5e?1如有侵犯,請聯絡study_golang @163.com刪除
最新教學 更多>
  • 在 Go 中使用 WebSocket 進行即時通信
    在 Go 中使用 WebSocket 進行即時通信
    构建需要实时更新的应用程序(例如聊天应用程序、实时通知或协作工具)需要比传统 HTTP 更快、更具交互性的通信方法。这就是 WebSockets 发挥作用的地方!今天,我们将探讨如何在 Go 中使用 WebSocket,以便您可以向应用程序添加实时功能。 在这篇文章中,我们将介绍: WebSocke...
    程式設計 發佈於2024-12-26
  • Bootstrap 4 Beta 中的列偏移發生了什麼事?
    Bootstrap 4 Beta 中的列偏移發生了什麼事?
    Bootstrap 4 Beta:列偏移的刪除和恢復Bootstrap 4 在其Beta 1 版本中引入了重大更改柱子偏移了。然而,隨著 Beta 2 的後續發布,這些變化已經逆轉。 從 offset-md-* 到 ml-auto在 Bootstrap 4 Beta 1 中, offset-md-*...
    程式設計 發佈於2024-12-26
  • 如何在 PHP 中組合兩個關聯數組,同時保留唯一 ID 並處理重複名稱?
    如何在 PHP 中組合兩個關聯數組,同時保留唯一 ID 並處理重複名稱?
    在 PHP 中組合關聯數組在 PHP 中,將兩個關聯數組組合成一個數組是常見任務。考慮以下請求:問題描述:提供的代碼定義了兩個關聯數組,$array1 和 $array2。目標是建立一個新陣列 $array3,它合併兩個陣列中的所有鍵值對。 此外,提供的陣列具有唯一的 ID,而名稱可能重疊。要求是建...
    程式設計 發佈於2024-12-26
  • 儘管程式碼有效,為什麼 POST 請求無法擷取 PHP 中的輸入?
    儘管程式碼有效,為什麼 POST 請求無法擷取 PHP 中的輸入?
    解決PHP 中的POST 請求故障在提供的程式碼片段中:action=''而非:action="<?php echo $_SERVER['PHP_SELF'];?>";?>"檢查$_POST陣列:表單提交後使用 var_dump 檢查 $_POST 陣列的內...
    程式設計 發佈於2024-12-26
  • 插入資料時如何修復「常規錯誤:2006 MySQL 伺服器已消失」?
    插入資料時如何修復「常規錯誤:2006 MySQL 伺服器已消失」?
    插入記錄時如何解決「一般錯誤:2006 MySQL 伺服器已消失」介紹:將資料插入MySQL 資料庫有時會導致錯誤「一般錯誤:2006 MySQL 伺服器已消失」。當與伺服器的連線遺失時會出現此錯誤,通常是由於 MySQL 配置中的兩個變數之一所致。 解決方案:解決此錯誤的關鍵是調整wait_tim...
    程式設計 發佈於2024-12-26
  • HTML 格式標籤
    HTML 格式標籤
    HTML 格式化元素 **HTML Formatting is a process of formatting text for better look and feel. HTML provides us ability to format text without us...
    程式設計 發佈於2024-12-26
  • 大批
    大批
    方法是可以在物件上呼叫的 fns 數組是對象,因此它們在 JS 中也有方法。 slice(begin):將陣列的一部分提取到新數組中,而不改變原始數組。 let arr = ['a','b','c','d','e']; // Usecase: Extract till index ...
    程式設計 發佈於2024-12-26
  • 如何在 HTML 表格中有效地使用 Calc() 和基於百分比的欄位?
    如何在 HTML 表格中有效地使用 Calc() 和基於百分比的欄位?
    在表格中使用Calc():克服百分比困境創建具有固定寬度列和可變寬度列的表格可能具有挑戰性,尤其是在嘗試在其中使用calc() 函數。 在 HTML 中,使用 px 或 em 設定固定列寬非常簡單。但是,對於可變寬度列,通常使用百分比 (%) 單位。然而,當在表中使用 calc() 時,百分比似乎無...
    程式設計 發佈於2024-12-26
  • 如何在PHP中透過POST提交和處理多維數組?
    如何在PHP中透過POST提交和處理多維數組?
    在PHP 中透過POST 提交多維數組當使用具有可變長度的多列和行的PHP 表單時,有必要進行轉換輸入到多維數組中。這是解決這項挑戰的方法。 首先,為每列分配唯一的名稱,例如:<input name="topdiameter[' current ']" type="...
    程式設計 發佈於2024-12-26
  • for(;;) 迴圈到底是什麼、它是如何運作的?
    for(;;) 迴圈到底是什麼、它是如何運作的?
    揭秘神秘的for(;;) 循環在古老的程式碼庫深處,你偶然發現了一個令人困惑的奇特for 循環你的理解。其顯示如下:for (;;) { //Some stuff }您深入研究線上資源,但發現自己陷入沉默。讓我們來剖析這個神秘的構造。 for 迴圈的結構Java 中的for 迴圈遵循特定的語...
    程式設計 發佈於2024-12-25
  • Java 的 Scanner.useDelimiter() 如何使用正規表示式?
    Java 的 Scanner.useDelimiter() 如何使用正規表示式?
    Java 使用Scanner.useDelimiter 了解分隔符號Java 中使用Scanner.useDelimiter 了解分隔符號Java 中的Scanner 類別提供了useDelimiter 方法,讓您指定分隔符號(代字或模式)來分隔代字幣。然而,使用分隔符號可能會讓初學者感到困惑。讓我...
    程式設計 發佈於2024-12-25
  • 如何在 Android 中顯示動畫 GIF?
    如何在 Android 中顯示動畫 GIF?
    在Android 中顯示動畫GIF儘管最初誤解Android 不支援動畫GIF,但實際上它具有解碼和顯示動畫的能力顯示它們。這是透過利用 android.graphics.Movie 類別來實現的,儘管這方面沒有廣泛記錄。 要分解動畫 GIF 並將每個幀作為可繪製對象合併到 AnimationDra...
    程式設計 發佈於2024-12-25
  • 為什麼我在執行 phpize 時出現「找不到 config.m4」錯誤?
    為什麼我在執行 phpize 時出現「找不到 config.m4」錯誤?
    解決phpize 中的“找不到config.m4”錯誤在運行phpize 時遇到“找不到config.m4”錯誤是可能阻礙ffmpeg 等擴充安裝的常見問題。以下是解決此錯誤並讓 phpize 啟動並運行的方法。 先決條件:您已經安裝了適合您的PHP 版本的必要開發包,例如php- Debian/U...
    程式設計 發佈於2024-12-25
  • 列印時如何在每頁重複表頭?
    列印時如何在每頁重複表頭?
    在印刷模式下重複表格標題當表格在印刷過程中跨越多個頁面時,通常需要有標題行(TH元素)在每頁重複,以便於參考。 CSS 提供了一種機制來實現此目的。 解決方案:使用 THEAD 元素CSS 中的 THEAD 元素是專門為此目的而設計的。它允許您定義一組應在每個列印頁面上重複的標題行。使用方法如下:將...
    程式設計 發佈於2024-12-25
  • 為什麼 `cout` 會誤解 `uint8_t` 以及如何修復它?
    為什麼 `cout` 會誤解 `uint8_t` 以及如何修復它?
    深入分析:為什麼 uint8_t 無法正確列印您遇到了 uint8_t 變數的值無法正確列印的問題庫特。經過調查,您發現將資料類型變更為 uint16_t 可以解決該問題。此行為源自於 uint8_t 的基本性質以及 cout 處理字元資料的方式。 uint8_t 在內部儲存一個無符號 8 位元整數...
    程式設計 發佈於2024-12-25

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3