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)); }
This function can be used in multiple ways:
As a one-liner:
await new Promise(r => setTimeout(r, 2000));
As a standalone function:
const sleep = ms => new Promise(r => setTimeout(r, ms));
As a typed function in TypeScript:
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
To use the sleep function, simply call it with the desired duration in milliseconds and await its resolution:
await sleep(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();
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!