October 20, 2011

Simple Javascript Delay routine

Setup events to occur after a delay

Using setTimeout we can trigger an alert after 5000 milliseconds.

setTimeout("alert('hello guest!')",5000);

<form>
	<input onclick="setTimeout('alert(\'hello\')',1250);" type="button" value="Click for event" />
</form>

That’s the elegant way to handle delays, pauses and waiting in Javascript.

Setup 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. Note: This script is not a good example of how to use Javascript. It consumes a huge amount of CPU power just going round in circles for a predetermined amount of time. You really should be using the technique above in nearly all cases, but this script can be handy for prototyping. Simple way:

<script language="javascript">

function dopause(msec) {
  msec += new Date().getTime();
  while (new Date() < msec){}
  } 

</script>

Call the routine dopause(5000) where 5000 is the number of milliseconds you would like the computer to pause. You're welcome to use this script on your site and to adapt it to suit.

JavaScript # , ,
Share: / / /

You might also like

Leave a Reply

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

Pin It on Pinterest

Share This