I'm trying to make a slideshow. I peek at some snippets and then try to recreate them without plainly copying. This is the snippet:
var slideIndex = 0;
showSlides();
function showSlides() {
var i;
var slides = document.getElementsByClassName("mySlides");
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
slideIndex++;
if (slideIndex > slides.length) {slideIndex = 1}
slides[slideIndex-1].style.display = "block";
setTimeout(showSlides, 2000); // Change image every 2 seconds
}
Well, what I do not understand how does the setTimeout works when the function was just called once, and why not to use setInterval outside the function. Thanks a lot.
The last thing showSlides
does is set a timeout to call itself again after 2 seconds. After that call finishes, it sets another timeout. That will continue forever.
In this case, there wouldn't be a noticeable difference if you used setInterval
. Both would accomplish the same thing. setInterval
would be easier to cancel though, which is an advantage.
Be sure to remove the call to setTimeout
in showSlides
if you do use setInterval
though:
var slideIndex = 0;
function showSlides() {
var i;
var slides = document.getElementsByClassName("mySlides");
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
slideIndex++;
if (slideIndex > slides.length) {slideIndex = 1}
slides[slideIndex-1].style.display = "block";
}
setInterval(showSlides, 2000);
To cancel the interval, capture the ID returned by setInterval
and call clearTimeout
:
let id = setInterval(showSlides, 2000);
clearTimeout(id); // This will clear and cancel the setInterval