Roaringdragon
Roaringdragon

Reputation: 3

Why doesn't this simple slideshow in javascript work?

I have the simple slideshow script below but it is showing only the last image. Why is it not showing each image with a 2500ms break between?

window.onload = myFunction;

var interval = 2500; 
var i = 0;
var images = ["1.png","2.png","3.png","4.png"]; 
var description = ["image1", "image2" , "image3" , "image4"];

function myFunction() {

    function setAttribute (number) {
        document.getElementById("image").src = images[number];
        document.getElementById("me").innerHTML = description[number];
    }

    function changeAttribute () {
        while (i < 4) {
            setAttribute(i);
            i++;
        }
    }

    setInterval(changeAttribute, interval);
}

Upvotes: 0

Views: 74

Answers (2)

Luk&#225;š Doležal
Luk&#225;š Doležal

Reputation: 289

Your changeAttribute cycle for first time interval call throught all images and stop on the last image. Since after that value of variable i is 4, nothing else happen never after. You have to for every interval call just set attributes with current value and change the value to next index. You can use modulo operator to cycle value within 0..images-1.

function changeAttribute () {
  setAttribute(i);
  i = (i+1) % images.length; 
}

Upvotes: 0

Jared Farrish
Jared Farrish

Reputation: 49188

You're iterating with a while loop, which means you're running through each option all at once; if you would have reset i = 0 on overrun, you would have had an infinite loop.

Use the setInterval() to do that instead:

window.onload = myFunction;

var interval = 2500;
var i = 0;
var images = ["1.png", "2.png", "3.png", "4.png"];
var description = ["image1", "image2", "image3", "image4"];

function myFunction() {
    setInterval(changeAttribute, interval);

    function setAttribute(number) {
        document.getElementById("image").src = images[number];
        document.getElementById("me").innerHTML = description[number];
    }

    function changeAttribute() {
        setAttribute(i);

        if (i < 3) {
            i++;
        } else {
            i = 0;
        }
    }

}

http://jsfiddle.net/6LQpu/

Upvotes: 4

Related Questions