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.

Pseudo

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.

Example

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. Finally, we invoke the delayedLoop function to start the loop.

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)
  }
}

delayedLoop();

Output

Each iteration of the loop is delayed by one second, as specified by the await delay(1000) statement.

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

Conclusion

In this article, we discussed how we can delay a loop in javascript using async/await with promises. This delay allows for more controlled and sequential execution of code, particularly useful in scenarios where we need to synchronize API calls, implement timed intervals, or introduce pauses for various reasons. The combination of async/await and Promises provides an elegant solution to delay loop execution without blocking the main thread of execution, making JavaScript programs more efficient and responsive.

Updated on: 17-Jul-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements