ClearTimeout () for setTimeout () for loop

clearTimeout()

inside the loop for

does not work

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

      

Fiddle: not working

Fiddle: working

Please help me stop setTimeout()

in the first script.

+3


source to share


1 answer


You will need to keep a reference to each timeout created in the loop and then repeat and clear each one, otherwise you will just overwrite myVar

with a new timeout without clearing the previous one and get lost 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

+7


source







All Articles