Search the Site

Sponsors

bottom corner

Javascript delay function

Sometimes we need to delay the execution of Javascript code for certain amount of time. This simple example allows that functionality.

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

The sample Javascript delay() function below performs a delay for X milliseconds. During the time specified, users can proceed to perform actions on the particular web page.

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

function delay(milliseconds) {
	var cmd = 'alert("Hello World!  This should have appeared after ' + milliseconds + ' milliseconds.");';
	setTimeout(cmd, milliseconds);
}

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


<script type="text/javascript">
function delay(milliseconds) {
	var cmd = 'alert("Hello World!  This should have appeared after ' + milliseconds + ' milliseconds.");';
	setTimeout(cmd, milliseconds);
}
</script>
<input type="button" onclick="javascript: delay(3000);" value="Do a 3-second delay">

If you are looking for a way to "freeze" the browser during the wait time, try the Javascript pause() 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