Setup events to occur after a delay

Using setTimeout we can trigger an alert after 5000 milliseconds.

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

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

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){}


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.

Leave a Reply

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

twelve − ten =

This site uses Akismet to reduce spam. Learn how your comment data is processed.

You May Also Like

qTip2 – Advanced jQuery Tooltip Plugin

qTip2 plugin can display the tooltip in any position wanted, plays nicely with image maps and they can be set to follow any element (handy for drag 'n' dropped and animated items) or mouse.

jQuery: Setting cookies

Setting and clearing cookies with jQuery is really easy but it's not included in the jQuery core and requires a plug-in. This post shows how to set, get the value of and clear cookies with jQuery.