What is JavaScript Version of Sleep()

Sleep is a popular function in many programming languages that allows a process to temporarily halt or sleep for a specified amount of time.

In JavaScript, there is no sleep() function, but we can achieve similar functionality using the setTimeout() method or the async/await syntax.

In this Javascript tutorial, we will take a closer look at both of these methods and how they can be used to implement sleep in JavaScript.


setTimeout()

The setTimeout() method is a non-blocking function that allows you to delay the execution of a piece of code.

It takes two arguments: the first is the function you want to run, and the second is the amount of time, in milliseconds, that you want to wait before running the function.

Example:

setTimeout(() => {
  console.log("Hello, World!");
}, 1000);

In this example, the message “Hello, World!” will be logged to the console after a one-second delay.

async/await

The async/await syntax is a newer method for implementing asynchronous code in JavaScript.

It allows you to write asynchronous code that looks and behaves like synchronous code.

To implement sleep in JavaScript using async/await, you can create a function that returns a promise that resolves after a specified amount of time.

Example:

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

async function run() {
  console.log("Starting sleep...");
  await sleep(1000);
  console.log("Sleep complete!");
}

run();

In this example, the message “Starting sleep…” is logged to the console, followed by a one-second delay, and finally the message “Sleep complete!” is logged to the console.


Conclusion

In conclusion, both the setTimeout() method and the async/await syntax can be used to implement sleep in JavaScript.

The setTimeout() method is a more traditional method for delaying the execution of code, while the async/await syntax allows you to write asynchronous code that looks and behaves like synchronous code.

Choose the method that best fits your needs and coding style.