Boo Shorty
Boo Shorty

Reputation: 15

I need to write an asynchronous function in JavaScript that sleeps for (millis) milliseconds and can resolve any value, but am unsure about await

I received this as a coding challenge, but am unfamiliar with the concepts of promises, awaits, and awaits.

// Asynchronous function that sleeps for a number of milliseconds
async function sleep(millis) {

    // Set timeout to new promise that resolves or rejects
    return new Promise((resolve, reject) => {

        setTimeout(() => new Promise((resolve, reject) => {

            // Call resolve
            resolve(millis);

        // Pass in milliseconds
        }), millis);

    });
        
};

/** 
 * let t = Date.now()
 * sleep(100).then(() => console.log(Date.now() - t)) // 100
 */

I'm unsure of what goes into calling back the resolve() function within the setTimeout(), what to pass in at the end of setTimeout(), and such.

Upvotes: 0

Views: 34

Answers (0)

Related Questions