Tilak Madichetti
Tilak Madichetti

Reputation: 4346

clearTimeout doesn't stop the loop

My script:

var pics = [ "mads.jpeg" ,"niggs.jpg", "rits.jpeg"];

var totalPics = pics.length;    
var frame = document.getElementById("photos");    
var i = 0;   

function loop() {

    if(i > (totalPics - 1)){                   
        clearTimeout(loopTimer);        
    }

    frame.innerHTML = '<img id="i" class="image" src="real_bs/'+pics[i]+'" />';
    i++;

    loopTimer = setTimeout(loop, 300);

}

loop();

When i exceeds totalPics - 1, the loop is not stopping, rather a small undefined image is being displayed. Why is clearTimeout(loopTimer) not stopping it? Is this an issue with variable scope?

Upvotes: 0

Views: 286

Answers (2)

Alnitak
Alnitak

Reputation: 339947

You don't even need to call clearTimeout - just arrange to only call setTimeout if there are more iterations left. A timeout that's never started doesn't have to be cleared:

(function loop() {

    frame.innerHTML = '<img id="i" class="image" src="real_bs/' + pics[i] + '" />';

    if (++i < totalPics) {
        setTimeout(loop, 300);
    }

})();  // invoke immediately

Upvotes: 3

Vignesh Murugan
Vignesh Murugan

Reputation: 575

Just add a simple return after your clearTimeout method call. Like this

if(i > (totalPics - 1)){                   
    clearTimeout(loopTimer);
    return;
}

Upvotes: 0

Related Questions