Approach 2 Using async/await

In this approach, the creation of the sleep() function in JavaScript can be done using async/await. We can code to create an async method that calls the sleep() function using the setTimeout() function.

Syntax:

async function sleep(time) {
    await new Promise(resolve => setTimeout(resolve, time));
}

In the above syntax, the sleep() function is defined as an async function that waits for the Promise returned by setTimeout() to resolve.

Example: Using async/await

Javascript
async function main() {
  console.log("Before sleep");
  await sleep(5000); // Sleep for 5 seconds
  console.log("After sleep [After 5 Seconds]");
}

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

main();

Output:

Explanation: In this example, we have defined the main function, but we have used the sleep() function that is been utilized through async/await. Here, we have given the amount of time as 5 seconds.

Both approaches provide ways to pause code execution for a specified duration, allowing us to control the flow of our JavaScript programs. Whether you choose the setTimeout() and Promises approach or the async/await approach depends on your preference and the requirements of your project.


What is the JavaScript version of sleep() method ?

In JavaScript, unlike some other programming languages, there is not a built-in sleep() function for pausing code execution. However, we can achieve similar effects through various approaches. One common approach involves delaying code execution for a specified duration of time. In this article, we will explore this approach in detail and demonstrate how to create a sleep() function effect in JavaScript.

Similar Reads

Approach 1: Using setTimeout() and Promises:

The setTimeout() function in JavaScript is used to delay the execution of a particular function with the time defined as a parameter. Using this function along with Promise can result in the creation of the sleep() function....

Approach 2: Using async/await:

In this approach, the creation of the sleep() function in JavaScript can be done using async/await. We can code to create an async method that calls the sleep() function using the setTimeout() function....

Contact Us