Search the Site

Sponsors

bottom corner

Javascript pause function

Sometimes we need to freeze a web page for a certain amount of time. This simple example allows that functionality.

This page is filed under keyword(s): javascript.

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.

Did you find this page useful? Please consider browsing other articles or subscribing to the RSS feed to keep up with latest.

This page is filed under keyword(s): javascript.
Author: C. Peter Chen
Last updated: 6 Apr 2010

bottom corner