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.
Next up, the setInterval() and clearInterval() methods. The main difference between these methods and the ones on the previous page is this: the setTimeout() and clearTimeout() methods are used to run a particular piece of code once after a pre-defined interval has passed, while the setInterval() and clearInterval() methods are used to run a piece of code over and over again, with a pre-defined interval between successive runs.
Consider the following example:
<script language="JavaScript"> var y = window.setInterval('alert("Yoohoo!")', 2000); </script>
In this case, the alert() box will keep appearing, once every 2 seconds. Thus, there are always two arguments to the setInterval() method – the first is the code to run, and the second is the amount of time between successive runs.
Here's another, more interesting example - creating a scrolling tickertape in the window's status bar:
<script language="JavaScript"> // ticket-tape message var message = " A blue pig jumped over the yellow moon "; // add and remove characters from the message function tickerTape() { window.status = message; message = message.substring(1, message.length) + message.substring(0, 1); } // start the ball rolling window.setInterval("tickerTape()", 150); </script>
In this case, I've created the appearance of a moving tickertape by taking one character off the beginning of the message string and adding it to the end. Each time the tickerTape() function is called, the first character of the string is deleted and added to the end of the string, simulating a scrolling ticker-tape. The setInterval() function takes care of calling the tickerTape() function over and over again, once every 150 milliseconds. Finally, the "status" property is used to assign the result at each stage to the browser's status bar.
Just as you can set an interval, you can also clear it with the clearInterval() method. Here too, you must provide clearInterval() with a reference so that it knows which interval to clear. The following variant of the example above demonstrates:
<html> <head> <script language="JavaScript"> // ticket-tape message var message = " A blue pig jumped over the yellow moon "; // add and remove characters from the message function tickerTape() { window.status = message; message = message.substring(1, message.length) + message.substring(0, 1); } // start the ball rolling var s = window.setInterval("tickerTape()", 150); </script> </head> <body> <form> <input type="button" value="Stop Scrolling" onClick="window.clearInterval(s)"> </form> </body> </html>
In this case, when you click the button, the clearInterval() method will cancel the timer set earlier with setInterval() and the tickertape will stop moving.