JavaScript's Window object comes with four methods that you can use to create timed or looping events in your Web pages. In this article, I'll introduce you to them, and also show you a few examples of how they can be used in different situations.
Let's start at the top, with the setTimeout() and clearTimeout() methods. These methods belong to the Window object, and are commonly used to run a particular piece of code after a pre-defined interval has passed. Consider the following example:
<script language="JavaScript"> var t = window.setTimeout('alert("5 seconds have passed since you loaded this page")', 5000); </script>
In this case, the setTimeout() method is used to run the function 5000 milliseconds (5 seconds). Thus, there are always two arguments to the setTimeout() method; the first is the code to run, and the second is the amount of time to wait before running it.
Here's another, more useful example.
<script language="JavaScript"> var t = setTimeout('window.close()', 30000); </script>
In this one, the window (which we'll assume has been popped open from some other parent window) closes automatically 30 seconds after it opens.
Just as you can set a timeout, you can also clear it with the clearTimeout() method. This method is used to remove a timeout previously declared with setTimeout(). Since there may be multiple calls to setTimeout() in the same document, it is mandatory to provide clearTimeout() with a reference so that it knows which timeout to clear. The following variant of the example above demonstrates:
<script language="JavaScript"> var t = window.setTimeout('window.close()', 30000); window.clearTimeout(t); </script>
In this case, the window will never close, because the clearTimeout() method will cancel the timeout previously created with setTimeout().
If you want to really obfuscate, you can clear a timeout after a specified interval, by wrapping the call to clearTimeout() in a call to setTimeout():
<script language="JavaScript"> var t = window.setTimeout('window.close()', 30000); var c = window.setTimeout('window.clearTimeout(t)', 10000); </script>
In this case too, the window will never close, because the first timeout will be cancelled 10 seconds in by the call to clearTimeout() in the second.