Good day all,
I am currently stuck with an issue here on javascript.
I have an automated slideshow loop based on this http://jsfiddle.net/pdb4kb1a/2.
Now I also have arrows added to the images so a user should be able to go back and forth himself as well. The problem here is, when I call on the onClick() it goes on re-calling the slideShow(n) method without 'interrupting' nor 'resetting' the other. So what I end up with is a recall on a loop while the other is still running, which creates a very fast and disorientated loop after clicking the arrow buttons.
How do I reset my slideShow() loop on call?
var imgArray = ['img/sleutels.jpg', 'img/naamborden.jpg', 'img/leer.jpg'];
var photoIndex = 2;
var photoId = document.getElementById('photoSlide');
function setIndex(n) {
slideShow((photoIndex + n));
}
function slideShow(n) {
photoId.className += "fadeOut";
setTimeout(appear, 500);
photoIndex++;
if (photoIndex == imgArray.length) {
photoIndex = 0;
}
console.log(photoIndex);
setTimeout(slideShow, 5000);
}
function appear() {
photoId.src = imgArray[photoIndex];
photoId.className = "";
}
slideShow();
Kind regards
For better structure I would nest the timeouts, then store the id of the timeout and clear it:
var appearId, showId;
function setIndex(n) {
slideShow((photoIndex + n));
}
function slideShow(n) {
photoId.className += "fadeOut";
photoIndex++;
if (photoIndex == imgArray.length) {
photoIndex = 0;
}
console.log(photoIndex);
if (appearId) { clearTimeout(appearId) }
appearId = setTimeout(appear, 500);
}
function appear() {
photoId.src = imgArray[photoIndex];
photoId.className = "";
if (showId) { clearTimeout(showId) }
showId = setTimeout(slideShow, 4500);
}
slideShow();