JavaScript Equivalent of sleep() Function

What is the JavaScript version of sleep()?

The typical way to mimic the sleep functionality in JavaScript is through promises and the setTimeout function. Here’s how you can implement a versatile sleep-like function:


function sleep(ms) {

return new Promise(resolve => setTimeout(resolve, ms));

}

You can also condense it into a one-liner for quick use:


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

For those using TypeScript, the same function can be typed as follows:


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

Usage is straightforward, you simply await the sleep function where needed:


await sleep(2000); // pauses execution for 2000 milliseconds

That’s a great explanation, Akansha! Building on your example, integrating sleep into asynchronous functions can make it even more practical. Here’s how you can utilize it within an async function to control the flow of operations:

async function example() {
  console.log('Hello');
  await sleep(2000); // Wait for 2 seconds
  console.log('World'); // Continues after the pause
}
example();

This pattern can be extremely useful in scenarios where you need a delay between sequential operations, like simulating network requests or pacing UI updates.

Indeed, and for those who prefer or require a callback-based approach, perhaps due to existing code patterns or specific use cases, you can adapt the sleep function to accept callbacks. This can be particularly useful when dealing with older JavaScript codebases or when integrating with libraries that rely heavily on callbacks:

function sleep(callback, ms) {
  setTimeout(callback, ms);
}

// Usage
sleep(() => {
  console.log('Hello after 2 seconds');
}, 2000);

While promises and async/await are more modern approaches, having the flexibility to use callbacks can be invaluable in certain situations.