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
Release: 2025-01-03 11:56:40
Original
725 people have browsed it

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));
}
Copy after login

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));
Copy after login

One-Line Syntax:

await new Promise(r => setTimeout(r, 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

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 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template