admin管理员组文章数量:1418019
What I'm trying to do is make slide out panels, but here is a simplified example of the problem I'm running into.
myCount = document.getElementById("counter")
myCount.onclick = startCount;
count = 0;
function startCount() {
timer = setInterval("countToTen()", 200);
}
function countToTen() {
count++;
myCount.innerHTML = count;
if (count >= 10) {
clearInterval(timer);
}
}
It works great if you click once. If you double click (and we can't trust users to only click when they're supposed to), then the counter goes on forever. I guess two timers got made, but Firebug is showing timer to always have the same id. So how do you use clearInterval correctly when setInterval got called twice?
What I'm trying to do is make slide out panels, but here is a simplified example of the problem I'm running into.
myCount = document.getElementById("counter")
myCount.onclick = startCount;
count = 0;
function startCount() {
timer = setInterval("countToTen()", 200);
}
function countToTen() {
count++;
myCount.innerHTML = count;
if (count >= 10) {
clearInterval(timer);
}
}
It works great if you click once. If you double click (and we can't trust users to only click when they're supposed to), then the counter goes on forever. I guess two timers got made, but Firebug is showing timer to always have the same id. So how do you use clearInterval correctly when setInterval got called twice?
Share Improve this question asked Apr 30, 2011 at 10:10 pennydropspennydrops 1491 gold badge2 silver badges7 bronze badges1 Answer
Reset to default 6var timer;
function startCount() {
if (!timer) {
timer = setInterval(countToTen, 200);
}
}
本文标签: javascriptsetInterval() won39t stop if it gets called twiceStack Overflow
版权声明:本文标题:javascript - setInterval() won't stop if it gets called twice - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745283001a2651535.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论