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.

Syntax:

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

In the above syntax, the sleep() function takes the parameter of ‘time’ that defines the number of milliseconds to pause the flow of execution. The function also returns the Promise that resolves after the amount of time has passed.

Example: Using setTimeout() and Promises

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

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

main();

Output:

 

Explanation: In this example, we have defined the main function that calls the sleep function with a time span of 2 seconds. The function displays the message before and after sleep in the console. 

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