Skip to content

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

  • by

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:

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

Use it in an Async function

const doSomething = async () => {
  await sleep(Time in ms)
  //do stuff
}

doSomething()

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.

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

Output:

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: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

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