Javascript pause function

The sample Javascript pause() function below performs a pause for X milliseconds. During the time specified, the browser would appear “frozen” to the user.

Quick reminder: 1000 milliseconds = 1 second, 60000 milliseconds = 1 minute

function pause(milliseconds) {
	var dt = new Date();
	while ((new Date()) - dt <= milliseconds) { /* Do nothing */ }
}

Below is a live example, followed by the HTML/Javascript code used.



<script type="text/javascript">
function pause(milliseconds) {
	var dt = new Date();
	while ((new Date()) - dt <= milliseconds) { /* Do nothing */ }
}

function preStuff() {
	alert('This is before the 3-second pause');
}

function postStuff() {
	alert('This is after the pause; it should have been paused for 3 seconds');
}

</script>

<input type="button" onclick="javascript: preStuff(); pause(3000); postStuff();" value="Do a 3-second pause">

If you are looking for a way to simply delay execution of code without "freezing" the browser during the wait time, try the Javascript delay() method.

Leave a Reply

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