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 the 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 the 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 the linear execution of code in JavaScript. Here we found a proper asynchronous way to pause a loop for a 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: the async keyword is mainly used while declaring a function.
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: The Promise actually does is that it traps the program execution inside it until it doesn’t gets resolved, and when it gets resolved after some time period it gives control back to the main method from where it was called.
Here, the waitforme function is the actual function that helps us in delaying the code which accepts one argument as a millisecond, which allows the 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 a separate JavaScript file and load it in chrome or try it in Node.js
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.