我有一个带有CountDown Timer功能的代码,
但我有一个问题,我无法解决 - 如果我点击按钮上的另一个时间,它会弄乱
如果它还在计算的话,我如何才能从新时间开始计算/或者不计算重复数?
为什么这样做?
function myFunctionTimer() {
var timeoutHandle;
function countdown(minutes) {
var seconds = 60;
var mins = minutes
function tick() {
var counter = document.getElementById("time");
var current_minutes = mins-1
seconds--;
counter.innerHTML =
current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
if( seconds > 0 ) {
timeoutHandle=setTimeout(tick, 1000);
}
if( seconds == 0 ) {
window.location.reload()
}else {
if(mins > 1){
setTimeout(function () { countdown(mins - 1); }, 1000);}}}tick();}
countdown(1);};
<button onclick="myFunctionTimer()">Click me</button>
<div class="OfertaWazna" >Counter: <span id="time"></span></div>
答案 0 :(得分:1)
您需要使超时变量可以访问到myFunctionTimer
,以便下次调用时清除相同的。
function myFunctionTimer( ele ) {
//attach the timer to the element
var tickTimer = ele.tickTimer;
if ( tickTimer )
{
clearTimeout( tickTimer );
}
// rest of the code
}
另外
addEventListener
代替onclick
,它不那么具有侵入性和可读性。<强>演示强>
function myFunctionTimer( ele ) {
//attach the timer to the element
var tickTimer = ele.tickTimer;
if ( tickTimer )
{
clearTimeout( tickTimer );
}
function countdown(minutes) {
var seconds = 60;
var mins = minutes
function tick() {
var counter = ele;
var current_minutes = mins - 1
seconds--;
counter.innerHTML =
current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
if (seconds > 0) {
ele.tickTimer = setTimeout(tick, 1000); //set the timer here
}
}
tick();
}
countdown(1);
}
document.querySelector( "button" ).addEventListener( "click", function(){
myFunctionTimer( document.getElementById( "time" ) );
});
<button>Click me</button>
<div class="OfertaWazna">Counter: <span id="time"></span></div>