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 *

5 × 2 =

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

You May Also Like

QUOjs – Micro JavaScript Library

QuoJS is a micro, modular, Object-Oriented and concise JavaScript Library that simplifies HTML document traversing, event handling, and Ajax interactions for rapid mobile web development. It allows you to write powerful, flexible and cross-browser code with its elegant, well documented, and micro coherent API.