javascript - setInterval() won't stop if it gets called twice - Stack Overflow

What I'm trying to do is make slide out panels, but here is a simplified example of the problem I&

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 badges
Add a ment  | 

1 Answer 1

Reset to default 6
var timer;
function startCount() { 
    if (!timer) {
        timer = setInterval(countToTen, 200);
    }
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745283001a4620390.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信