javascript async delay
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function exampleAsyncFunction() {
console.log('Start of async function');
await delay(2000); // Delay for 2000 milliseconds (2 seconds)
console.log('After 2 seconds');
await delay(3000); // Delay for an additional 3000 milliseconds (3 seconds)
console.log('After another 3 seconds');
}
exampleAsyncFunction();
Define a function named
delay
that returns a promise, which resolves after a specified time delay.Create an asynchronous function named
exampleAsyncFunction
.Log a message indicating the start of the async function.
Use the
await
keyword to pause execution of the async function for 2000 milliseconds using thedelay
function.Log a message indicating that 2 seconds have passed.
Use the
await
keyword again to pause execution for an additional 3000 milliseconds using thedelay
function.Log a message indicating that another 3 seconds have passed.
Call the
exampleAsyncFunction
to execute the asynchronous function.