©Sean McManus - www.sean.co.uk
Photo of Sean McManus with John Lennon graffiti RSSwww.sean.co.uk

UK writer, author and freelance journalist Sean McManus

Blog Shop Books Articles Photos Games Links Help Freebies Email
www.sean.co.uk RSS
UK writer and author Sean McManus

Nintendo DS Browser: Start here

Blog Shop Books Articles Photos
Games Links Help Downloads © Contact
You are here: Home > Articles > Webmaster resources > Javascript delay

Javascript delay / wait / pause routine

My first programming language was Basic. There is a command to jump from one line of the program to another, called GOTO. I've heard it said that this command is never needed (in Basic) if you're writing structured programs and programming properly. Certainly, I can't think of a good exception.

I mention this because I wonder whether this Javascript delay script is a similar dark force that shouldn't ever be needed if you're programming well. I'll share it with you anyway and let you worry about the beauty of your code.

Setting events to occur after a delay

This is the right way to make something happen after a delay, using setTimeout to trigger an alert after 1250 milliseconds.
setTimeout("alert('hello')",1250);
Want to see it in action? No problem.
And here's the code that pulls that stunt:
<form>
<input type="button" value="Push this button to open an alert box in 1250 milliseconds" onClick="setTimeout('alert(\'hello\')',1250);">
</form>
That's the elegant way to handle delays, pauses and waiting in Javascript. Your teacher would be proud of you.

Setting a Javascript program to wait

The routine above doesn't stop the Javascript routine from executing. It just sets up an event to happen later.

But sometimes you find yourself thinking: It would be so much easier if I could just get Javascript to wait for a bit here and then carry on as before.

It's a bit naughty, but I've written a script that does just that.

<script language="javascript">

// www.sean.co.uk

function pausecomp(millis)
{
var date = new Date();
var curDate = null;

do { curDate = new Date(); }
while(curDate-date < millis);
}

</script>

Call the routine pausecomp(x) where x is the number of milliseconds you would like the computer to pause.

Many thanks to Michael Andrews who adapted my original code for seconds to make it work for milliseconds and Artur Kraft who sent me this code, which is more elegant than my original solution was. Thanks also to André Pirard for untwisting the variable declarations.

You're welcome to use this script on your site and to adapt it to suit.

Short appeal

If you found this page useful, please consider linking to my website or checking out these other ways you can help support this site.

Recommended Javascript books

Where next?

©1987-2008 Sean McManus | Top