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

How Can I Efficiently Implement a Sleep Function in Modern JavaScript?

Barbara Streisand
Barbara StreisandOriginal
2025-01-03 11:56:40671browse

How Can I Efficiently Implement a Sleep Function in Modern JavaScript?

Crafting an Effective Sleep Solution in JavaScript: A Modern Approach

While the pausecomp function offers a rudimentary solution for inducing a pause in JavaScript, contemporary standards demand a more efficient and elegant approach. This article presents the current best practice for achieving a "real sleep" within a function in JavaScript, which has evolved since 2009.

The Superior Sleep Function

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

This function leverages the Promise API, a built-in feature introduced in ECMAScript 2015, to create a Promise that represents the asynchronous sleeping operation. After the specified number of milliseconds (ms) have elapsed, the resolve function is invoked, which in turn triggers the continuation of the execution.

Usage Examples

As a Function:

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

One-Line Syntax:

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

Demo:

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

demo();

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

Statement:
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
Previous article:JavaScript vs. TypeScriptNext article:JavaScript vs. TypeScript