Open In App

What is the JavaScript version of sleep() method ?

Last Updated : 27 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In JavaScript, there is no sleep() function like in other programming languages. Similar effects can be done using various approaches. Approaches like Pausing the execution of the code for a specific amount of time. In this article, we will dive deep into this type of approach and also we will create the sleep() function effect in JavaScript.

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. 

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.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads