This is for creating a single event which will happen after a set time:
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:
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:
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.