Open In App

How to delay a loop in JavaScript using async/await with Promise ?

Last Updated : 27 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In JavaScript, you can delay a loop by using async/await with Promise. By wrapping a setTimeout() inside a Promise and using await, you can pause execution at each iteration, creating delays between loop iterations for asynchronous tasks without blocking the main thread.

What is async and await?

async and await in JavaScript are used for handling asynchronous operations. async declares a function as asynchronous, while await pauses the function’s execution until a Promise is resolved, enabling cleaner, non-blocking code.

Syntax:

async function delay() {
    return new Promise(resolve => {resolve()})
}

JavaScript await makes a function wait for a Promise: await is mainly used while calling a function.

Syntax:

await delay();

Approach: A Promise in JavaScript pauses code execution until it resolves, returning control to the calling method once completed. The waitforme function delays code for a specified duration in milliseconds, allowing controlled pauses during asynchronous execution.

Example: This example shows the use of the above-explained approach.

JavaScript
function waitforme(millisec) {
    return new Promise(resolve => {
        setTimeout(() => { resolve('') }, millisec);
    })
}

async function printy() {
    for (let i = 0; i < 10; ++i) {
        await waitforme(1000);
        console.log(i);
    }
    console.log("Loop execution finished!)");
}

printy();

 Output:

0
1
2
3
4
5
6
7
8
9
Loop execution finished!)

Note: We can change the value of the parameter of waitforme function while calling the function to increase/decrease the delay in the code.



Next Article

Similar Reads