Matt Ellis Matt Ellis - 4 months ago 28
Javascript Question

Javascript slider loop

I have been trying to create an image slider for html by changing the value of the image element, using a loop to go through each image and then returning to the original image.

However once it reaches the end of the loop it doesn't continue.

Here is my Js code:



window.onload = function() {
var x = 0
while(x<1000){
setTimeout(function() {
document.getElementById('carousel').src='img/header2.jpg';
setTimeout(function() {
document.getElementById('carousel').src='img/header3.jpg';
setTimeout(function() {
document.getElementById('carousel').src='img/header.jpg';
}, 5000);
}, 5000);
}, 5000);
x = x+1
}
}




Answer

I'd recommend you to not do while loop in this case. Just recall setTimeout when executed.

window.onload = function() {
     /* Element */
    var carousel = document.getElementById('carousel'),
     /* Carousel current image */
    cimage = 2,
     /* Carousel source images */
    csources = [
        'img/header2.jpg',
        'img/header3.jpg',
        'img/header.jpg'
    ];

    function changeCarouselImage() {
        // Reset the current image if it's ultrapassing the length - 1
        if(cimage >= 3) cimage = 0;
        // Change the source image
        carousel.src = csources[cimage ++];
        // Re-call the function after 5s
        setTimeout(changeCarouselImage, 5000);
    }

    setTimeout(changeCarouselImage, 5000);
};
Comments