Register Login

JavaScript Sleep

Updated Jan 08, 2023

To pause execution in any programming language for a fixed amount of time, programmers use the sleep() function, which is also possible in JavaScript. Unlike other programming languages, JavaScript does not allow the execution of a built-in sleep() function.

Either the user needs to create a custom sleep()  function using the built-in setTimeout() function, or they can use the latest ECMAScript promises like the async-await function. This article will show how to use the JavaScript sleep function and the alternative method for using sleep from an external code to get the functionality of the sleep function.

What is meant by JavaScript sleep?

The working of JavaScript has an asynchronous action. So, it allows users to use the Promise object to deal with all asynchronous actions. Along with the JavaScript Promise, some other functions and methods can prove to be helpful to execute sleep kind of functionality in JavaScript, like the async/await functions.

As we have already discussed, JavaScript does not have any sleep function. Users have to use an alternative way to pause or delay their program. First, we will discuss how to use the sleep function and execute the JavaScript code to understand the notion of the JavaScript sleep Function.

Syntax of sleep function:

sleep(delayTime in milliseconds).then(() => {  
// code to be executed  
})

Users can use the sleep function to pause the current thread execution for a fixed time in Milliseconds. Here, the thread does not lose its ownership of the monitor and continues its implementation.

JavaScript programmers use the sleep() function with the await or async to obtain a pause in the program execution. Let us see some examples and learn how to use a custom sleep function in a JavaScript program:

  1. Custom Javascript sleep using the Promise function (Asynchronous)
  2. Custom JavaScript sleep without using the Promise function (Synchronous)

Example 1: JavaScript sleep using Promise function with async or await functionalities

Code Snippet:

<html>  
<head>
	<title>Custom sleep function in JavaScript</title>
</head>  
<body>  
<h1> Custom sleep function in JavaScript </h1>  
<script>  
   function sleep(milliseconds) {  
      return new Promise(resolve => setTimeout(resolve, milliseconds));  
   }  
   async function function1() {  
      document.write('We are going to learn sleep');  
      for (let i = 1; i <=5 ; i++) {          
         await sleep(2000);  
         document.write( i + ". " + "Hey, this is JavaScript sleep function" + " " + "</br>");  
      }  
   }  
   function1();  
</script>
</body>  
</html>

Output:

Run Code Snippet

Explanation:

We used the sleep() function with the async/await functionalities in the above code snippet. Then we use a JS function named "function1()," and we define it with random statements. At first, the text "We are going to learn sleep" is displayed on the screen once the function starts. Then, the sleep() function pauses the operation of function function1() for four seconds.

After four seconds, the JavaScript engine displays the subsequent text "Hey, this is JavaScript sleep function" on the screen and repeats it until the for loop terminates. The function will repeat the text five times on the screen with a pause of four seconds on each iteration of the for loop.

Example 2: JavaScript Sleep with the custom sleep function:

The setTimeout() function will run the code after the specified time interval.

Code Snippet:

<html>  
<head>
	<title>Custom sleep function in JavaScript</title>
</head> 
<body>  
<h1> Here, we are applying the custom sleep function in JavaScript program </h1>  
<script>
	setTimeout(function(){
		document.write("Hey, this is JavaScript sleep function");
	}, 2000);
</script>
</body>  
</html>

Output:

Run Code Snippet

Explanation:

The browser will display the message "Hello, we are calling the JavaScript sleep function" after five seconds or five-thousand milliseconds. Here, we have used the custom sleep function that specifies the required time interval.

Synchronous version of sleep function:

Experts and professionals strongly discourage the use of Date.prototype.getTime() function inside a while loop to pause execution for a specified duration of time. But, still, if users want to pause the execution, they can use the custom sleep() function for synchronous actions, which is as follows:

Code Snippet:

<html>  
<head>
	<title>Custom sleep function in JavaScript</title>
</head>  
<body>  
<h1>Synchronous version of sleep function</h1>  
<script>  
const sync = (milliseconds) => {
  const a = new Date().getTime() + milliseconds;
  while (new Date().getTime() < a) { /* This will execute nothing */ }
}
const numbers = () => {
  console.log(1);
  document.write(1); 
  sync(1000);
  console.log(2);
  document.write(2); 
  sync(1000);
  console.log(3);
  document.write(3); 
  sync(1000);
  console.log(4);
  document.write(4); 
  sync(1000);
  console.log(5);
  document.write(5); 
};
numbers();  
</script>
</body>  
</html>

Output:

Run Code Snippet

Explanation:

Here, we have used the while loop. It will print the numbers from one to five with a gap of 1000 milliseconds. The function numbers() will start the execution of the while loop.

Asynchronous version of sleep function:

It is the least efficient and intrusive way to implement the sleep() function with the "await" and "async" keywords added in JavaScript ES6 with the JavaScript Promise and setTimeout() still; if users want to pause their code execution, they can try this out.

But users must execute the resulting function in the async function and should call it with the await.

Code Snippet:

<html>  
<head>
	<title>Custom sleep function in JavaScript</title>
</head>  
<body>  
<h1>Asynchronous version of sleep function</h1>  
<script>  
const a = (ms) =>
  new Promise(resolve => setTimeout(resolve, ms));
const numbers = async() => {
  console.log(1);
  document.write(1);	
  await a(1000);
  console.log(2);
  document.write(2);
  await a(1000);
  console.log(3);
  document.write(3);
  await a(1000);
  console.log(4);
  document.write(4);
  await a(1000);
  console.log(5);
  document.write(5);
  await a(1000);
};
numbers();   
</script>
</body>  
</html>

Output:

Run Code Snippet

Another example of the sleep() function is as follows:

Programmers can efficiently execute the sleep functionality by using the setTimeOut(), but it is crucial to assess the asynchronous behavior of the setTimeout() function.

Let us understand this with the help of the following code snippet:

<html>  
<head>
	<title>Custom sleep function in JavaScript</title>
</head>   
<body>  
<h1>This is an example of the sleep() function in JavaScript </h1>  
<p>There is a time gap of 4000 milliseconds</p>  
<script>  
	let a = milliseconds => {  
		return new Promise(resolve => setTimeout(resolve, milliseconds));  
	};  
	document.write("Start" + "<br>");  
	document.write("Hey, this is JavaScript sleep function" + "<br>");
	
	a(4000).then(() => { 
		document.write("Finish");  
	});  
</script> 
</body>  
</html>

Output:

Run Code Snippet

Explanation:

In the code snippet, we have created a JavaScript Promise object with the setTimeout() function. The setTimeout() function will run the code after the given period.

We are also operating the then() method, which performs the required function after the completion of the promise.

At first, the JavaScript engine displays the initial texts, then after a delay of four seconds, it will display the text "Finish" on the screen.  Output:

Conclusion:

In JavaScript, users cannot directly use the sleep() functions, unlike other programming languages. However, as mentioned above, there is an alternative option for using the sleep function by making our custom sleep function with the methods.

The await and async keywords help to create JavaScript that is readable and efficient and write the JavaScript code a breeze.


×