Home >Web Front-end >JS Tutorial >How Can I Efficiently Implement a Sleep Function in Modern JavaScript?
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.
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.
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!