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.

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.

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.


Contact Us