Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can't pause slideshow with cleartimeout

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading