Home > Web Front-end > JS Tutorial > How Can I Implement a Modern JavaScript Sleep Function Using Promises?

How Can I Implement a Modern JavaScript Sleep Function Using Promises?

DDD
Release: 2024-12-28 02:47:10
Original
715 people have browsed it

How Can I Implement a Modern JavaScript Sleep Function Using Promises?

A Modern Approach to JavaScript Sleep: Introducing the Promise-Based Solution

Since its inception in 2009, JavaScript has undergone significant transformations. The once-popular pausecomp function for creating a "real" sleep within a function has become outdated. Today, a more efficient and versatile approach awaits us.

The modern JavaScript sleep version relies on the power of Promises. Using the new Promise() constructor, we can create a promise that resolves after a specified number of milliseconds. By using the await keyword, we can pause execution of the function until the promise is resolved, effectively achieving the desired sleep behavior.

Here's the updated code snippet:

function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}
Copy after login

This function can be used in multiple ways:

As a one-liner:

await new Promise(r => setTimeout(r, 2000));
Copy after login

As a standalone function:

const sleep = ms => new Promise(r => setTimeout(r, ms));
Copy after login

As a typed function in TypeScript:

const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
Copy after login

To use the sleep function, simply call it with the desired duration in milliseconds and await its resolution:

await sleep(2000);
Copy after login

Demo:

async function demo() {
    for (let i = 0; i < 5; i++) {
        console.log(`Waiting ${i} seconds...`);
        await sleep(i * 1000);
    }
    console.log('Done');
}

demo();
Copy after login

This updated approach not only simplifies the sleep implementation but also provides a modern and efficient solution that leverages the asynchronous nature of JavaScript.

The above is the detailed content of How Can I Implement a Modern JavaScript Sleep Function Using Promises?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template