Create wait function by passing resolve to setTimeout

Create wait function by passing resolve to setTimeout

Placing the resolve function of a Promise inside a setTimeout function, and then awaiting that Promise, effectively creates a wait or sleep mechanism in JavaScript. This is due to the interplay of Promises, setTimeout, and the async/await syntax.

Here's a breakdown:

How it creates a wait

Consider this common pattern:

function delay(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}
async function myFunction() {
    console.log("Starting...");
    await delay(2000); // This line pauses execution for 2 seconds  
    console.log("After 2 seconds...");
}
myFunction();

In this example:

This combination effectively creates a wait or sleep behavior because the async function's execution is halted until the Promise that's tied to the setTimeout resolves, signifying the completion of the desired delay.

Expand codes to view full details

// Customize resolve function.
//  Replace resolve with () => {}.
//  It means from top level Promise, it is passing resolve() to setTimeout().
//  setTimeout() is executing a callback function that happens to be an anonymous function.
//  That anonymous function is executing the resolve().
function delay(ms) {
    return new Promise(resolve => setTimeout( () => { resolve("I'm done") } , ms));
}
async function myFunction() {
    console.log("Starting...");
    const result = await delay(2000); // This line pauses execution for 2 seconds  
    console.log(result); // Logs "I'm done" after 2 seconds
    console.log("After 2 seconds...");
}
myFunction();

/* OUTPUT:

Starting...
I'm done
After 2 seconds...

*/