5

clearTimeout() inside for loop doesn't work

for(i=0;i<10;i++){
    myVar = setTimeout(function(){
        alert("Hello")
    }, 3000);
}

Fiddle : not working

Fiddle : working

Please help me to stop setTimeout() in first Fiddle.

1 Answers1

12

You'll have to keep a reference to each timeout created in the loop, and then iterate and clear each one, otherwise you're just overwriting the myVar with a new timeout without clearing the previous one, and loosing the reference as you go etc.

$(document).ready(function(){
    var myVar = []

    $("#myfunction").click(myFunction);
    $("#mystopfunction").click(myStopFunction);

    function myFunction() {
        for(i=0;i<10;i++){
            myVar.push(
                setTimeout(function(){
                    alert("Hello")
                }, 3000)
            );
        }
    }

    function myStopFunction() {
        myVar.forEach(function(timer) {
            clearTimeout(timer);
        });
    }
});

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388
  • Exactly what I was going to suggest. The code in the original post overwrites the value of `myVar`, and so only the last timeout is affected by `clearTimeout`. – jrad Aug 14 '14 at 15:32
  • Man, you've saved my life :D – EPurpl3 Oct 25 '19 at 14:21