0

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);        

}
rainwilds
  • 31
  • 3

1 Answers1

1

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

Ihor Vyspiansky
  • 918
  • 1
  • 6
  • 11
  • Well that is brilliant Ihor. Just a follow up. Why do you have this 'const changeImage = function()' and not just 'function changeImage() {}'? What's the need to assign the function to a variable? Sorry for the noob questions. :/ – rainwilds Aug 14 '20 at 12:38
  • I guess, you can replace each other in this example. I had no particular purpose. Just a matter of habit. You can read about the difference here https://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname – Ihor Vyspiansky Aug 14 '20 at 12:45