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.
1 Answer
Reset to default 12You'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
版权声明:本文标题:javascript - clearTimeout() for setTimeout() in for loop - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741522659a2383280.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论