2014-03-29 46 views
0

我有一些代码用于在15秒后从15秒倒计时,它会回应“超过”时间。问题是如果有人点击两次,同一分区会有两个计数器。如果有人再次点击按钮,我需要重置计数器。重置计数器OnClick

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> 

回答

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"); 
} 
+0

尝试过,但它似乎已经打破了它,但无论如何谢谢你 – puppet

+0

我忘了提及,你还必须设置定时器作为一个变量之前的功能。我添加到我的答案的代码适用于我。 – Jabbath

+0

我看到这已经得到了相当数量的意见。回到我的工作中,我只是不想使用全局变量。在这之后我很快看到这不是问题。 ES6虽然处理得更好。 – puppet