I am creating a web widget where I am trying to load images from the multiple directories based on the option selected from the drop-down list. If I select option 1, it should pick the first directory and loads the images from that directory with an interval of 7 seconds. If I select Option 2, it should select a different directory and loads images from that directory with an interval of 7 seconds. I am using setInterval option in Javascript. When I select the option 1, it works fine and loads images one by one with the time interval of 7 seconds but when I select the option 2 in the drop-down list the time interval gets reduced from 7 seconds. I tried using clearInterval by following a few solutions but it didn't work for me. I also referred How do I correctly use setInterval and clearInterval to switch between two different functions?.
Below is my code :
selectCity.addEventListener("change", () => {
celeb.src = `${directory}/image1.png`;
images = [];
images[0] = `/${directory}/image1.png`;
images[1] = `/${directory}/image2.png`;
images[2] = `/${directory}/image3.png`;
var setint = window.setInterval(changeImage, 7000);
var x = 1;
function changeImage() {
celeb.src = images[x];
console.log(images[x]);
x++;
if (images.length == x) {
x = 0;
window.clearInterval(setint);
setint = window.setInterval(changeImage, 7000);
}
}
}
I want to use clearInterval, once selectCity gets changed. I am beginner to HTML and Javascript. Please suggest what am I doing wrong in this code.