Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Vòng lặp bất đồng bộ (Asynchronous Loop) trong JavaScript


Dùng async/await trong vòng lặp for...of hoặc for thông thường để chờ mỗi lần lặp (sequential). Không dùng forEach vì nó không chờ await. Để chạy song song: Promise.all(arr.map(...)).

Ví dụ

Vòng lặp 0-9, mỗi lần chờ 2 giây (sequential):

<!DOCTYPE html>
<html lang="vi">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Async Loop JS</title>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
    .result { font-size: 20px; font-weight: 500; color: blueviolet; }
  </style>
</head>
<body>
  <h1>Vòng lặp bất đồng bộ (Asynchronous Loop) trong JavaScript</h1>
  <div class="result"></div>
  <button class="Btn">BẮT ĐẦU LOOP</button>
  <h3>Nhấn nút để chạy loop async (mỗi lần 2 giây)</h3>
  <script>
    const resEle = document.querySelector(".result");
    const wait = (ms) => new Promise(r => setTimeout(r, ms));
    async function runLoop() {
      for (let i = 0; i < 10; i++) {
        await wait(2000);
        resEle.innerHTML += `i = ${i}<br>`;
      }
    }
    document.querySelector(".Btn").addEventListener("click", runLoop);
  </script>
</body>
</html>

Kết quả

Sau 2s: in 0. Sau 4s: in 1... Tổng ~20s in hết 0-9.

Lưu ý: Dùng for...of cho mảng. forEach không support await. Song song: await Promise.all(items.map(item => process(item))).