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 look at a couple more examples, which demonstrate just how useful - and varied - these functions can be. This first one uses the setInterval() method to create a timed slideshow:
<html> <head> <script language="JavaScript"> // slideshow image counter var i = 0; function slideShow() { // set up list of images slidesArray = new Array()
// when at the end, start again if(i==5) { i=0; } } </script> </head> <body onLoad="javascript:setInterval('slideShow()',5000);"> <img src="image1.jpg" name="image"> </body> </html>
Here, the images to be displayed are stored in a JavaScript array, and a "for" loop takes care of pulling out the correct image from the array and loading it into the page. The setInterval() method is used to refresh the image with a new one every 5 seconds.
You can also use the setInterval() method to move things around on a Web page, by incrementing an X- or Y-coordinate of a page element at a predefined interval. Consider the following example, which demonstrates by moving a <div> containing an image of a car across the screen.