moonshineOutlaw
moonshineOutlaw

Reputation: 723

setTimeout not recalling function javascript

I have a list of images that I want to iterate through as a slideshow. I've set up a basic function to display an image then used setTimeout to recall the function and move onto the next image.

The function is only being called once and displays just the one image. I've checked the syntax of setTimeout I'm sure it's correct. Is there a fault in my code somewhere else that is causing this ?

<img id='screenImg' src='' height='300' width='450'/>

function slideshow() {

var screenImg = document.getElementById('screenImg');
var gradImg = ['images/grad1.jpg', 'images/grad2.jpg', 'images/grad3.jpg',   'images/grad4.jpg', 'images/grad5.jpg', 'images/grad6.jpg',];
var gradAmt = gradImg.length-1;
var i = 0;

if( i > gradAmt ) {
  i = 0;
}
screenImg.src = gradImg[i];
i++;
var timer = setTimeout(slideshow, 1000);
}
slideshow();        

Upvotes: 0

Views: 234

Answers (1)

Quentin
Quentin

Reputation: 943207

You reset i to 0 each time slideshow is called.

Move var i = 0; so it is outside the function.


Since it won't be local to the function any more, consider giving it a more explicit name, such as slideshow_index

Upvotes: 3

Related Questions