The important point is that JavaScript does not do precise timing well. It is primarily event-driven with the user providing the events. It can create it's own events with timers in two ways though.


This is for creating a single event which will happen after a set time:

setTimeout("alert('Hi')", 10000);

This will pop up a dialog box after 10 seconds. If the browser is busy then there may be an additional delay.  The speech marks (double quotes) are there because otherwise the browser will see the alert and run it straight away.  It shows that the stuff inside is not code it is text to be used by setTimeout.

If you call the setTimeout slightly differently you can also cancel it:

timer1=setTimeout("alert('Hi')", 10000);

To cancel that timer:



Sometimes you might want to do something every second (or minute etc.). In a Web application you might want to auto-save work unless the user manually saves it. To do this many people use the setTimeout timer to call a function and at the beginning or end of the function create the timer again. If the user does save manually then cancel the original timer and start a new one.

However, the correct way is to use setInterval. The syntax is the same as setTimeout:

timer1=setInterval("alert('Hi')", 10000);

The difference is that now you get a dialog box every ten seconds! You can use cancelInterval in the same way as cancelTimeout above.

Multiple instances of setTimeout or set Interval

One possible problem with setInterval is that the user may trigger more than one instance and so duplication or contradiction may occur. Your code will need to allow for this (maybe by setting the variable (here timer1) to undefined when it is not tracking an active interval or timeout. Then use an IF statement to check that it is undefined before starting it up again.