javascript sleep – How to Make JavaScript Sleep or Wait?

javascript sleep Delay, Pause, & Wait Example also Javascript does not have a built-in sleep function. & JavaScript setTimeout Tutorial – How to Use the JS Equivalent of sleep, wait, delay, and pause.

javascript sleep

In the bellow example, i have used the sleep() with async/await js method. Here sleep js method is accompanied with await to continue the proceedings. Initially the text in the async js method “Gretting Pakainfo” is displayed once the js method is started.

Later on, the js method is paused using sleep js method for 5 seconds. Once the time time is completed, the text(“Greeting to ……..”) bellow the sleep js method 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 result.

Syntax of sleep() in JavaScript

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

JavaScript Sleep() function?






Output

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

What is the Javascript alternative to the sleep function?

console.log("Greeting");
setTimeout(() => {  console.log("Pakainfo!"); }, 2000);

Don’t Miss : PHP Sleep Delay Function

I hope you get an idea about javascript sleep.
I would like to have feedback on my infinityknow.com.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

Leave a Comment