【发布时间】:2020-06-20 23:11:10
【问题描述】:
对于第一次尝试将它用于学校项目的 JS,我完全是个菜鸟。
我的目标是有一个在按下按钮时倒计时的计时器。然后使用未来 10 分钟的 Unix 时间作为参数调用 countdownClock 函数。我的代码似乎运行良好,但再次按下按钮时,它会产生一个奇怪的交替故障,其中两个计时器同时运行。
如何在按下按钮时忘记前一个计时器?谢谢!
function countdownClock(time){
// Set the date we're counting down to
var countDownDate = (time + "000");
// Update the count down every 1 second
var x = setInterval(function() {
// Get today's date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Output the result in an element with id="demo"
document.getElementById("timer").innerHTML = minutes + "m " + seconds + "s ";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("timer").innerHTML = "GAME OVER";
}
}, 1000);
}
【问题讨论】:
-
也添加您的 html 代码,而不是我们试图猜测您的 html 代码是什么...
-
你能不能为此创建一个jsfiddle.net,我很难理解你在做什么。或者,也添加您的 html
-
那是因为每次点击按钮都会创建一个新作业,而之前的间隔作业只是继续工作。
标签: javascript html time timer