开发者

setInterval() won't stop if it gets 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?


var timer;
function startCount() { 
    if (!timer) {
        timer = setInterval(countToTen, 200);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜