JavaScript sleep() Function

JavaScript sleep() Function | The sleep(sec) function is available in programming languages like PHP and C to suspend the execution for a set period. Java thread contains the sleep() method. Similarly, Python has time, where can we use sleep().

In contrast to other languages, JavaScript lacks a sleep() function. We can simulate the JavaScript sleep() function using several methods. JavaScript’s capabilities, like promises and the async/await function, made it easy for us to use the sleep() function.

The await can only be used in async functions and to wait for a promise. JavaScript’s behavior is asynchronous; therefore, promises are a concept to deal with this asynchronous nature.

Syntax of sleep() function in JavaScript:-

sleep(delayTime in milliseconds).then(() => {
  // executable code
});

The async/await method can be used in conjunction with the sleep() function to create a pause in execution. The following is the provided syntax for the same:-

const func = async () => {
  await sleep(delayTime in milliseconds);
  //executable code
};
func();

JavaScript sleep() Function Example

This example combines the async/await functionalities with the sleep() function. A few statements define a function named fun(). The message “Hello” is initially shown on the screen when the function is activated.

The fun() function is then halted for 2 seconds thanks to the sleep function. The phrase “Welcome to Know Program” will appear on the screen after the allotted time has passed and will keep repeating until the loop is broken. The text will be displayed ten times on the screen with a two-second break between each loop iteration.

function sleep(milliseconds) {
  return new Promise((resolve) => setTimeout(resolve, milliseconds));
}
async function fun() {
  console.log("Hello");
  for (let i = 1; i <= 10; i++) {
    await sleep(2000);
    console.log(i + " " + "Welcome to Know Program" + " ");
  }
}
fun();

Output:-

Hello
1 Welcome to Know Program
2 Welcome to Know Program
3 Welcome to Know Program
4 Welcome to Know Program
5 Welcome to Know Program
6 Welcome to Know Program
7 Welcome to Know Program
8 Welcome to Know Program
9 Welcome to Know Program
10 Welcome to Know Program

The output will change after two seconds. The loop will repeat 10 times, pausing every time for 2 seconds.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *