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