An image gallery: Start the slide show

  1. An endless slide show
  2. An image gallery
  3. Wait for idle time

Now we have an object that keeps track of the slides and can advance through them. We need a function to get up that object (to do the “gallery=new SlideShow()” for us) and a function to regularly advance through the slides.

//create a gallery and start the slide show in motion

function beginShow() {

gallery = new SlideShow();

window.setTimeout(advanceSlide, 30000);

}

//advance the slide show, and set the timer for the next advance

function advanceSlide() {

gallery.advance();

window.setTimeout(advanceSlide, 5000);

}

In the URL bar, type “javascript:beginShow()” and wait 30 seconds. After 30 seconds it should advance to the second slide, and then advance every five seconds afterwards.

Add beginShow to the windows’ onload and the show will start up 30 seconds after the page loads.

window.onload=beginShow;

You can see in these two functions why we need gallery to be global (which is why we don’t create it using “var gallery = …”). The gallery variable is created in one function but used in the next. If it were created using “var”, it would only be available in the function that created it.

Start the slide show: Timers

The window object is your doorway to the visitor’s computer—as much of a doorway as you’re going to get. It includes a method for telling the browser to run some code at a later time. The setTimeout method accepts a function and a number of milliseconds as its parameters. In beginShow above, we’re telling the browser to run the advanceSlide function in 30,000 milliseconds (30 seconds). Every time it runs advanceSlide, the last thing advanceSlide does is tell the browser to run advanceSlide in 5000 milliseconds (5 seconds).

Timers are the reason we have to put the control code in a separate function instead of in a method on the SlideShow class. If we try to have the timer call a method on gallery, it will happily call that method—but without any of the context of the method being part of an object. It will lose track of “this” and apply it to the window instead of to the gallery object.

  1. An endless slide show
  2. An image gallery
  3. Wait for idle time