JavaScript Page 2 - Using Timers in JavaScript |
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: 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.
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:
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(): 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.
blog comments powered by Disqus |