简体   繁体   中英

How can I make this slide code snippet loop infinetly ( my current code is not working and I don't know where I'm making mistakes)

I have a JavaScript file with the following CODE:

var slideArray = new Array();
slideArray[0] = new Image();
slideArray[0].src = "images/slide/1.jpg";
slideArray[1] = new Image();
slideArray[1].src = "images/slide/2.jpg";
slideArray[2] = new Image();
slideArray[2].src = "images/slide/3.jpg";
slideArray[3] = new Image();
slideArray[3].src = "images/slide/4.jpg";
slideArray[4] = new Image();
slideArray[4].src = "images/slide/5.jpg";

var step = 0;

function slideit() {
    if (!document.images)
        return;
    document.getElementById('slide').src = slideArray[step].src;
    if (step < 5)
        step++;
    else
        step = 0;
    setTimeout("slideit();", 4500);
}

slideit();

This piece of code gets all the images from my directory and sets their path to an image element on the page.

After that I call a function slideit() in the code which iterates through all the images and calls itself afterwards recursively through a call made by a setTimeout() function at every 4500 milliseconds.

The problem is that it doesn't turn on again after it iterates through 4 of my images and it doesn't display the last one and I don't know how to solve this problem. Any advice of code example is welcome, thanks in advance !

@fuyushimoya helped me out solving the problem. It seemed that inside the function I was checking step variable to see if it was higher than 5 and that made the function not working properly ... no everything is working fine and and step doesn't get the value 5 anymore which would of made it out of boundary at document.getElementById('slide').src = slideArray[step].src; as he stated.

Thanks a lot @fuyushimoya for helping me on this one ! Million thanks !

You can use the length of the array for testing, like here with a reminder operator.

 function slideit() { document.getElementById('slide').src = slideArray[step].src; step++; step %= slideArray.length; } var step = 0, slideArray = new Array(); slideArray[0] = new Image(); slideArray[0].src = "http://lorempixel.com/100/50/"; slideArray[1] = new Image(); slideArray[1].src = "http://lorempixel.com/100/51/"; slideArray[2] = new Image(); slideArray[2].src = "http://lorempixel.com/100/52/"; slideArray[3] = new Image(); slideArray[3].src = "http://lorempixel.com/101/50/"; slideArray[4] = new Image(); slideArray[4].src = "http://lorempixel.com/102/50"; if (document.images) { slideit(); setInterval(slideit, 4500); } 
 <img id="slide" width="100" height="50" /> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM