Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to implement asynchronous loop in JavaScript?
Asynchronous loops in JavaScript allow you to perform time-delayed or async operations within loops without blocking the main thread. This is essential when working with APIs, file operations, or timed delays.
What is an Asynchronous Loop?
A regular loop executes all iterations instantly. An asynchronous loop waits for each iteration to complete before moving to the next, using await with async functions.
Using async/await with for Loop
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Asynchronous Loop</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.result {
font-size: 18px;
font-weight: 500;
color: blueviolet;
margin: 20px 0;
}
.btn {
background-color: #4CAF50;
color: white;
padding: 10px 20px;
border: none;
cursor: pointer;
border-radius: 4px;
}
</style>
</head>
<body>
<h1>Asynchronous Loop in JavaScript</h1>
<div class="result"></div>
<button class="btn">Start Async Loop</button>
<p>Click the button to see numbers appear every 2 seconds.</p>
<script>
let resEle = document.querySelector(".result");
// Helper function to create delay
async function waitTime(time) {
return new Promise((resolve) => {
setTimeout(resolve, time);
});
}
// Asynchronous loop function
async function asyncLoop() {
resEle.innerHTML = "Starting async loop...<br>";
for (let i = 1; i <= 5; i++) {
await waitTime(2000); // Wait 2 seconds
resEle.innerHTML += `Iteration ${i} completed<br>`;
}
resEle.innerHTML += "<strong>Loop finished!</strong>";
}
document.querySelector(".btn").addEventListener("click", () => {
asyncLoop();
});
</script>
</body>
</html>
Output
When you click the "Start Async Loop" button, you'll see each iteration appear after a 2-second delay, demonstrating how the loop waits for each async operation to complete.
Alternative Approaches
Using forEach with async (Not Recommended)
// This WON'T work as expected - all delays run simultaneously
[1, 2, 3, 4, 5].forEach(async (num) => {
await waitTime(1000);
console.log(num); // All numbers appear at once after 1 second
});
Using Promise.all() for Parallel Execution
// All promises run in parallel
async function parallelLoop() {
const promises = [1, 2, 3, 4, 5].map(async (num) => {
await waitTime(1000);
return `Number: ${num}`;
});
const results = await Promise.all(promises);
console.log(results); // All complete after 1 second total
}
Comparison Table
| Method | Execution | Use Case |
|---|---|---|
| async/await with for loop | Sequential (one after another) | When order matters or rate limiting needed |
| Promise.all() | Parallel (all at once) | When operations are independent |
| forEach with async | Unpredictable | Not recommended for async operations |
Key Points
- Use
async/awaitwithforloops for sequential async operations - Avoid
forEachwith async functions - it doesn't wait - Consider
Promise.all()when operations can run in parallel - Always handle errors with try/catch blocks in async loops
Conclusion
Asynchronous loops using async/await with for loops provide controlled, sequential execution of async operations. This pattern is essential for handling API calls, file processing, or any scenario requiring timed delays between iterations.
