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 delay a loop in JavaScript using async/await with Promise?
Some time?consuming tasks are executed without blocking the main thread in Asynchronous programming. In certain cases, developers may need to delay the execution of a loop to control the flow of their program or introduce delays between iterations. JavaScript provides several techniques for delaying execution, and in this article, we will explore how to delay a loop using the combination of async/await and Promises.
Understanding async/await
The async/await syntax was introduced in ECMAScript 2017 (ES8) and provides a concise and readable way to write asynchronous code. It is built on top of Promises and allows developers to write asynchronous code in a synchronous manner. The async keyword is used to declare an asynchronous function, and the await keyword is used to pause the execution of the function until a Promise is resolved or rejected.
Using Promises for Delay
Promises are JavaScript objects that represent the eventual completion or failure of an asynchronous operation. By utilizing Promises, we can introduce delays in our code execution. We can create a Promise that resolves after a specified duration using the setTimeout function.
Syntax
async function functionName() {
// Asynchronous code
const result = await promise;
// Execution pauses until the promise is resolved
// Code after await is executed when the promise is resolved
}
Here,
The async keyword is used to declare an asynchronous function. It can be placed before a function declaration, function expression, or arrow function.
The function body contains the code that will be executed asynchronously
The await keyword is used to pause the execution of the function until the Promise is resolved or rejected.
The await keyword can only be used inside an async function.
The promise represents a Promise object that is being awaited. It can be any Promise, such as the result of an asynchronous operation or a manually created Promise.
Note
The use of await can only be done within an async function.
Await can be used with any expression that returns a Promise (e.g., async function, API call, setTimeout, etc.).
Using await allows you to write asynchronous code in a more synchronous and readable manner.
Creating a Delay Function
First, let's create a simple delay function that returns a Promise which resolves after a specified time:
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
// Test the delay function
async function testDelay() {
console.log("Starting delay...");
await delay(2000); // Wait 2 seconds
console.log("Delay completed!");
}
testDelay();
Starting delay... [waits for 2 seconds] Delay completed!
Example: Basic Delayed Loop
In the below example, we define a function delay that returns a Promise. This Promise resolves after a specified duration (ms) using setTimeout and the resolve callback. Next, we declare an async function delayedLoop that will perform the delayed loop. Inside the delayedLoop function, we use a traditional for loop with a loop variable `i` to iterate five times. For each iteration, we log a message indicating the current iteration number using console.log. We then use the await keyword followed by the delay function, passing the desired delay duration of 1000 milliseconds (1 second). This causes the execution of the loop to pause for the specified delay duration before proceeding to the next iteration.
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function delayedLoop() {
for (let i = 0; i < 5; i++) {
console.log(`Iteration ${i}`);
await delay(1000); // Delaying for 1 second (1000 milliseconds)
}
console.log("Loop completed!");
}
delayedLoop();
Iteration 0 [waits for 1 second] Iteration 1 [waits for 1 second] Iteration 2 [waits for 1 second] Iteration 3 [waits for 1 second] Iteration 4 Loop completed!
Example: Delayed Loop with Array Processing
Here's a practical example where we process an array with delays between each item:
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function processArrayWithDelay() {
const items = ['apple', 'banana', 'cherry', 'date'];
for (let i = 0; i < items.length; i++) {
console.log(`Processing item ${i + 1}: ${items[i]}`);
await delay(800); // Wait 800ms between items
}
console.log("All items processed!");
}
processArrayWithDelay();
Processing item 1: apple [waits for 800ms] Processing item 2: banana [waits for 800ms] Processing item 3: cherry [waits for 800ms] Processing item 4: date All items processed!
Common Use Cases
API Rate Limiting: Preventing too many requests per second
User Interface Animation: Creating smooth transitions between states
Data Processing: Giving the browser time to update the UI between heavy operations
Simulating Real-world Delays: Testing how applications handle slow operations
Conclusion
The combination of async/await and Promises provides an elegant solution to delay loop execution without blocking the main thread. This technique is particularly useful for controlling execution flow, managing API calls, and creating responsive applications. By using await with a Promise-based delay function, you can create predictable pauses in your loops while maintaining code readability.
