JavaScript sleep function | Make a function to pause execution for the time

First JavaScript doesn’t have inbuilt sleep functions instead You can use the setTimeout or setInterval functions. But you can make the custom sleep function in JavaScript. It will pause execution for a fixed amount of time.

JavaScript sleep function Example

Use this with the then callback:

Use it in an Async function

Complete example code:

Here is the HTML example code where we used the sleep() with async/await function. A function is accompanied with await to continue the proceedings.


JavaScript sleep function pause execution for the time

When the page loaded the text in the async function “Hello World” is displayed once the function is started. Later on, the function is paused using the sleep function for 1 second.

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 5 times as shown in the output. 

Q: Is there a sleep function in JavaScript?

Answer: Unlike Java or Python, JavaScript does not have a built-in sleep function.

Do comment if you have any doubts and suggestions on this topic.

Note: All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.