It is very easy to create an animation loop with Javascript . How to Make Web Page Animations Using Javascript shows how an image can be moved around the display area of a web browser using the setTimeout method.
The command is used by a function to call itself after a short interval (for example 10ms) and this creates an infinite loop which can be used to animate a web page object. And, of course, this infinite loop can also be used to produce other effects on the web page. Effects such as a slide show.
Creating an Infinite Loop with setTimeout
The infinite loop is created by making a function call itself after a set time period (in this case 1 second):
Here the function reset the timer when ever it runs, however it does not run automatically. The function mas be called from Javascript in order to set the loop in motion:
Nothing obvious will happen if this is viewed in a web browser, but something more definite can be seen with a little more code:
This time the web browser will be seen to continually count from 0 to 9. It's this simple technique that can be adapted to create a simple slide show.
Creating a Slide Show with setTimeout
The first step of creating a slide show is to set where the images are to be located and which is the default image:
The next step is to define an array with the names (or the url if they are in a different location to the web page) of the images to be used in the slide show (examples of which can be seen in Figures 1-3 at the bottom of this article). The array is created by using the "new" method:
And then the programmer can then create the animation that will produce the slide show:
It is worth noting here how the length of the array is used to determine when the loop should be reset to zero, and that the loop count is then used as the index number for the image to be loaded. This means that if the code is saved into a .html file and viewed in a web browser then the user will see a slide show that reveals a fresh image once every second.