Open In App

How to Make JavaScript Sleep or Wait?

Last Updated : 27 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In JavaScript, there is no built-in sleep function like in some other programming languages. However, you can create a delay or pause in code execution by using asynchronous methods.

We can use setTimeout() or Promise along with async/await to achieve this functionality for more readable code.

1. Using setTimeout() and Promises

The setTimeout() function is used to schedule a function to run after a specified delay. By combining it with Promises, we can create a custom sleep() function that pauses code execution for a defined time.

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

Output

How to Make JavaScript Sleep or Wait

2. Using async/await Keyword

You can simplify the code and improve readability by using async/await with the sleep function. The await keyword pauses the execution of the function until the Promise returned by the sleep function is resolved.

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

Output

How to Make JavaScript Sleep or Wait

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.



Next Article

Similar Reads