admin管理员组

文章数量:1290984

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.

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.

Share Improve this question asked Aug 14, 2014 at 15:28 user3941922user3941922
Add a ment  | 

1 Answer 1

Reset to default 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

本文标签: javascriptclearTimeout() for setTimeout() in for loopStack Overflow