Rotating Images using an array and the setInterval(x,n) function

The functions setTimeout() and setInterval() appear to be very similar.

The setTimeout() function delays for a specified time period and then triggers execution of a specified function. Once the function is triggered the setTimeout() has finished. You can terminate the execution of the setTimeout() before it triggers an action by using the clearTimeout() function. But that is just about it.

The setInterval() function also delays for a specified time before triggering the execution of an action. Where it differs is, that after triggering an action the command doesn't complete - it just waits for the specified time again and then triggers the function again and again. It continues to repeat this process of triggering the function at the specified intervals until either the web page is unloaded or the clearInterval() function is called.

The setInterval() function is used for many slideshow presentations. It will execute a simple function at a set interval as long as the window state is active.

To set up a simple slide show you need three things.
- You need a function with an array of images,
- a global variable that increments each time the function is run,
- and a timer that executes at a given time interval.
See the code below:

var i = 0; function slideShow() { // set up list of images image = new Array() image[0] = '../images/MMPI01_m.jpg' image[1] = '../images/MMPI02_m.jpg' image[2] = '../images/MMPI03_m.jpg' image[3] = '../images/MMPI04_m.jpg' image[4] = '../images/Dragon01_n.jpg' image[5] = '../images/Dragon02_m.jpg' image[6] = '../images/Hush01_m.jpg' image[7] = '../images/Hush02_m.jpg' image[8] = '../images/Hush03_m.jpg' image[9] = '../images/Hush04_m.jpg' // load image document.images.image.src=image[i] // increment counter i=i+1; // when at the end, start again if(i==9) { i=0; } } The only thing left to do is to set up the HTML to display the images. This is done by adding a form with the specific image id or name used in the function, and an on load event to triggerthe slideshow function. . . . <body onLoad="javascript:setInterval('slideShow()',2000);"> . . . <form name="images"> <img src="../images/MMPI01_m.jpg" name="image" style="position:relative; float:right; margin:10px;"> </form> . . .
There you have it...
back