JavaScript Sleep() function?


Sleep()

With the help of sleep() we can make a function to pause execution for a fixed amount of time. In programming languages such as C and PHP we would call sleep(sec). Java has thread.sleep(), Python has time.sleep() and Go has time.Sleep(2 * time.Second).

JavaScript doesn't have these kinds of sleep functions. But we should thank promises and async/await function in ES 2018. Because these features have helped us to use sleep() as easy as possible. Let's discuss it in a nutshell.

syntax-1

sleep(Time in ms).then(() => {
//// code
})

We can use the sleep function with then call back as shown above.

syntax-2

const work = async () => {
await sleep(Time in ms)
//code
}
work()

We can use the sleep() function with async/await function as shown above.

Example

In the following example, we have used the sleep() with async/await function. Here sleep function is accompanied with await to continue the proceedings. Initially the text in the async function "Hello Tutorix" is displayed once the function is started. Later on, the function is paused using sleep function for 3 seconds. Once the time period is completed, the text("Welcome to ........") following the sleep() function is displayed. It is repeated until the loop terminates, meaning that in total the text is going to be repeated for 19 times as shown in the output. 

<html>
<body>
<script>
   function sleep(ms) {
      return new Promise(resolve => setTimeout(resolve, ms));
   }
   async function Tutor() {
      document.write('Hello Toturix');
      for (let i = 1; i <20 ; i++) {        
         await sleep(3000);
         document.write( i +" "+"Welcome to tutorix" + " " + "</br>");
      }
   }
   Tutor()
</script>
</body>
</html>

Output

Hello Tutorix
// after 3 secs
1 Welcome to tutorix
// after 3sec...and the text will repeat until the loop terminates for every 3 sec
2 Welcome to tutorix
3 Welcome to tutorix
4 Welcome to tutorix
5 Welcome to tutorix
6 Welcome to tutorix
7 Welcome to tutorix
8 Welcome to tutorix
9 Welcome to tutorix
10 Welcome to tutorix
11 Welcome to tutorix
12 Welcome to tutorix
13 Welcome to tutorix
14 Welcome to tutorix
15 Welcome to tutorix
16 Welcome to tutorix
17 Welcome to tutorix
18 Welcome to tutorix
19 Welcome to tutorix

Updated on: 02-Sep-2023

47K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements