Core JavaScript

Using a Sleep Function

The Promise() function can be used to create a sleep function to delay the execution of program.

SleepFunction.html

<!DOCTYPE html>
<html>
<head>
    <title>XoaX.net's Javascript</title>
    <script type="text/javascript" src="SleepFunction.js"></script>
</head>
<body onload="SleepTest()">
    <div id="idDiv"></div>
</body>
</html>

SleepFunction.js

async function SleepTest() {
	qDiv = document.getElementById("idDiv");
	qDiv.innerHTML = "";
	for (var i = 0; i < 10; ++i) {
		// Sleep for 1 second
		qDiv.innerHTML += "<div>Sleeping for "+i+" second"+((i != 1)? "s":"")+"...zzz</div>"
		await new Promise(fnWait => setTimeout(fnWait, i*1000));
		qDiv.innerHTML += "<div>Done</div>"
	}
}
 

Output

 
 

© 2007–2025 XoaX.net LLC. All rights reserved.