rainwilds
rainwilds

Reputation: 31

Making a Slideshow Delay Image Cycling Using JS & JQuery

I'm trying to create little slideshow using JS and JQuery. The code below works (sort of) but doesn't delay before showing the next image; just shows it right away. I'm trying to get it too delay for 5sec before showing the next image. I'm a bit of a novice so apologies if the code is dodgy.

*The URLs have been changed to make it more readable.

Thanks for helping!

var backgroundImg = ["https://x1.jpg", "https://x2.jpg"];
var backgroundImgLength = backgroundImg.length;

var z = 0;

do {

        slideShow(backgroundImg[z]);
        z++;

}
while (z < backgroundImgLength);

function slideShow(url) {

    setTimeout(function() {
        
        $('.header-section').css('background-image', 'url(' + url + ')');

    }, 5000);        

}

Upvotes: 0

Views: 36

Answers (1)

Ihor Vyspiansky
Ihor Vyspiansky

Reputation: 916

I would try to use it in this way:

const backgroundImg = [
    "https://picsum.photos/id/237/200/300",
    "https://picsum.photos/id/239/200/300"
];
const backgroundImgLength = backgroundImg.length;

let backgroundImgIndex = 0;
let backgroundImgUrl = backgroundImg[backgroundImgIndex];

const changeImage = function() {
    $('.header-section').css('background-image', 'url(' + backgroundImgUrl + ')');
}

const getNextImgIndex = function() {
    return (backgroundImgIndex + 1 < backgroundImgLength) ? backgroundImgIndex + 1 : 0;
}

// setInterval allows us to run a function repeatedly,
// starting after the interval of time,
// then repeating continuously at that interval.
const timerId = setInterval(function() {
    backgroundImgIndex = getNextImgIndex();
    backgroundImgUrl = backgroundImg[backgroundImgIndex];
  
    changeImage();
}, 5000);

changeImage();

Please have a look here https://codepen.io/vyspiansky/pen/jOqqNmQ

Upvotes: 1

Related Questions