我在js中进行了计时器倒计时。它在单击事件后运行。问题是,当我再次单击计时器时,计时器不会重置并且创建了另一个倒计时,但前一个倒计时仍然在计时。当我再次单击时,我想重置第一个。
我尝试使用一个清晰的间隔,但是我不确定使用它是否正确。
function countdownto(target, time, callback) {
var finish = new Date(time);
var s = 1000,
m = s * 60,
h = m * 60,
d = h * 24;
(function timer() {
var now = new Date();
var dist = finish - now;
var days = Math.floor(dist / d),
hours = Math.floor((dist % d) / h),
minutes = Math.floor((dist % h) / m),
seconds = Math.floor((dist % m) / s);
var timestring = minutes + ' minute(s) ' + seconds + ' seconde(s)';
target.innerHTML = timestring
if (dist > 0) {
setTimeout(timer, 1000);
} else {
callback()
}
})()
}
var submitBtn = document.getElementById('yes');
submitBtn.addEventListener("click", function(e) {
// countdown element
var countdownel = document.getElementById('clockdiv');
// 20 min
var time = new Date()
time.setSeconds(time.getSeconds() + 1200)
// countdown function call
countdownto(countdownel, time, function() {
alert('end');
})
})
<button id="yes"></button>
<div><span id="clockdiv">countdown
</span></div>
答案 0 :(得分:2)
您需要清除每次点击的最后一次超时。
为此,创建一个全局变量并将超时分配给该变量。每次点击后可以使用clearTimeout
观看现场演示
var timeout;
function countdownto(target, time, callback) {
var finish = new Date(time);
var s = 1000,
m = s * 60,
h = m * 60,
d = h * 24;
(function timer() {
var now = new Date();
var dist = finish - now;
var days = Math.floor(dist / d),
hours = Math.floor((dist % d) / h),
minutes = Math.floor((dist % h) / m),
seconds = Math.floor((dist % m) / s);
var timestring = minutes + ' minute(s) ' + seconds + ' seconde(s)';
target.innerHTML = timestring
if (dist > 0) {
timeout = setTimeout(timer, 1000);
} else {
callback()
}
})()
}
var submitBtn = document.getElementById('yes');
submitBtn.addEventListener("click", function(e) {
clearTimeout(timeout)
// countdown element
var countdownel = document.getElementById('clockdiv');
// 20 min
var time = new Date()
time.setSeconds(time.getSeconds() + 1200)
// countdown function call
countdownto(countdownel, time, function() {
alert('end');
})
})
<button id="yes">yes</button>
<div><span id="clockdiv">countdown
</span></div>
注意:您使用setTimeout模拟setInterval
。我认为最好直接使用setInterval
答案 1 :(得分:1)
setTimeout(timer,1000)返回内部计时器ID。要停止在setTimeout()中传递的函数,您必须通过调用clearTimeout(ID)函数来停止计时器,并传递从setTimeout()获得的内部计时器ID 我也建议您使用setInterval():
var myVar = setInterval(myTimer, 1000);
function myTimer() {
var d = new Date();
document.getElementById("demo").innerHTML = d.toLocaleTimeString();
}
停止myTimer
功能清除myVar
clearTimeout(myVar);