Skip to content
Related Articles

Related Articles

How to delay a loop in JavaScript using async/await with Promise ?
  • Difficulty Level : Basic
  • Last Updated : 31 Dec, 2020

Given below is a JavaScript code snippet which is basically described how to delay a loop in JavaScript using async/await. In this article, we are using JavaScript either by web browser or Node.js. We all face a difficult situation in delaying a loop in JavaScript unlike C++ where we have sleep() function, but there is nothing like this in JavaScript. All we have in JavaScript is setTimeout() function, but this is not what we look for when we have a bulk of code to execute after some delay, as a result there come conflicts in linear execution of code in JavaScript. Here we found a proper asynchronous way to pause a loop for specific time as we used to do in C++ or C.

What is async and await?

Async and await make promises easier to write. The async keyword makes a function return a promise : async keyword is mainly used while declaring a function.

Syntax:

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

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



Syntax:

await delay();

Approach: The Promise actually does is that it traps the program execution inside it until it doesn’t get resolved, and when it gets resolved after some time period it gives control back to the main method from where it was called.

Here, waitforme function is the actual function which helps us in delaying the code which accepts one argument as milisecond, which allows user to delay code for a duration of his/her choice.

To understand Promises in deep you should visit:  https://www.geeksforgeeks.org/javascript-promises

You can directly copy and paste the code below to the console and check it or you can create separate JavaScript file and load it in chrome or try it in Node.js

Example:

Javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

function waitforme(milisec) {
    return new Promise(resolve => {
        setTimeout(() => { resolve('') }, milisec);
    })
}
  
async function printy() {
    for (let i = 0; i < 10; ++i) {
        await waitforme(1000);
        console.log(i);
    }
    console.log("Loop execution finished!)");
}
  
printy();

chevron_right


Output:

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

full-stack-img

My Personal Notes arrow_drop_up
Recommended Articles
Page :