重置计数器OnClick

时间:2014-03-29 01:11:40

标签: javascript jquery

我有一些代码,我用它从15秒开始倒计时15秒后回复“时间结束”。问题是如果有人点击两次,同一个Div中会有两个计数器。如果有人再次点击按钮,我需要重置计数器。

function startCountDown(i, p, f) {
    // store parameters
    var pause = p;
    var fn = f;
    // make reference to div
    var countDownObj = document.getElementById("countDown");
    if (countDownObj == null) {
        // error
        alert("div not found, check your id");
        // bail
        return;
    }
    countDownObj.count = function (i) {
        // write out count
        countDownObj.innerHTML = i;
        if (i == 0) {
            // execute function
            fn();
            // stop
            return;
        }
        setTimeout(function () {
            // repeat
            countDownObj.count(i - 1);
        },
        pause);
    }
    // set it going
    countDownObj.count(i);
}

function myFunction() {
    alert("Time Over");
} 

HTML:

<div id="TimerTitle">Timer</div>    
<span id="countDown"></span>
<button onclick="startCountDown(15, 1000, myFunction);">
    Start Time
</button>

2 个答案:

答案 0 :(得分:1)

将超时设置为全局变量,如下所示:

timer = setTimeout(function(){countDownObj.count(i - 1);},pause);

在功能开始时清除超时

clearTimeout(timer)

代码:

var timer;
function startCountDown(i, p, f) {
// store parameters
if(timer){clearTimeout(timer)}
var pause = p;
var fn = f;
// make reference to div
var countDownObj = document.getElementById("countDown");
if (countDownObj == null) {
    // error
    alert("div not found, check your id");
    // bail
    return;
}
countDownObj.count = function (i) {
    // write out count
    countDownObj.innerHTML = i;
    if (i == 0) {
        // execute function
        fn();
        // stop
        return;
    }
timer = setTimeout(function(){countDownObj.count(i - 1);},pause);
}
// set it going
countDownObj.count(i);
}

function myFunction() {
alert("Time Over");
} 

答案 1 :(得分:0)

setTimeout会向可以与window.clearTimeout一起使用的计时器返回 id 。最简单的解决方案是创建全局timerId

var timerId; 
...

function startCountDown(i, p, f) { 
    ...
    if (timerId) { window.clearTimeout(timerId); }
    timerId = window.setTimeout(...);

https://developer.mozilla.org/en-US/docs/Web/API/Window.setTimeout