So I'm learning javascript and I'm currently working on an assignment where I need to create a banner that cycles through multiple images with a pause button, problem is, I can't seem to pause it with clearTimeout()
var images = [];
var timer;
images[0] = 'destaque-home.png';
images[1] = 'destaque-home-1.png';
images[2] = 'destaque-home-2.png';
function changeImg(){
document.MoveBanner.src = images[i];
if(i < images.length - 1){
i++;
} else {
i = 0;
}
var timer = setTimeout("changeImg()", 1000);
console.log(timer);
}
function LeftArrow() {
i--;
if (i < 0){
i=2;
}
document.MoveBanner.src = images[i];
}
function RightArrow() {
document.MoveBanner.src = images[i];
i++;
if (i > 2){
i=0;
}
}
function PauseBut() {
clearTimeout(timer);
}
window.onload = changeImg;```
var timer = setTimeout("changeImg()", 1000);
Because you used var
, the variable you create is not the same as the global var timer
variable declared at the top of the code. That means that the PauseBut function is trying to clearTimeout with the wrong timer
.
To instead use the globally scoped timer
:
timer = setTimeout("changeImg()", 1000);