gpt4 book ai didi

javascript - 可以重置而不重叠的计时器? - JavaScript

转载 作者:行者123 更新时间:2023-12-02 21:32:11 25 4
gpt4 key购买 nike

我对 JS 完全是个菜鸟,第一次尝试在学校项目中使用它。

我的目标是拥有一个按下按钮即可倒计时的计时器。然后调用 countdownClock 函数,并以 future 10 分钟的 Unix 时间作为参数。我的代码似乎工作得很好,但再次按下按钮时,它会产生一个奇怪的交替故障,两个计时器同时运行。

按下按钮后我该怎么做才能忘记之前的计时器?谢谢!


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);
}

最佳答案

我猜你是从某个地方复制的,因为它已经有你需要的东西 - clearInterval 会给你你正在寻找的结果,你应该只需要很少的改变

var intervalId;
function countdownClock(time){
// Set the date we're counting down to
var countDownDate = (time + "000");
// clear the old one, if relevant
if (intervalId)
clearInterval(intervalId)
intervalId = 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(intervalId);
document.getElementById("timer").innerHTML = "GAME OVER";
}
}, 1000);
}

关于javascript - 可以重置而不重叠的计时器? - JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60594169/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com