Javascript delay function

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.

Leave a Reply

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