gpt4 book ai didi

Javascript - 基本秒表可以多次启动,提高 watch 速度。解决方案?

转载 作者:太空宇宙 更新时间:2023-11-04 15:52:50 25 4
gpt4 key购买 nike

这是我们的 JS 代码(基本上是从其他地方复制粘贴的),它或多或少可以工作,但我们有一个问题,如果用户多次单击“开始”按钮, watch 的速度会随着时间的推移而增加每个按钮按下。

var h1 = document.getElementsByTagName('h1')[0],
start = document.getElementById('start'),
stop = document.getElementById('stop'),
clear = document.getElementById('clear'),
seconds = 0, minutes = 0,
t;

function add() {
seconds++;
if (seconds >= 60) {
seconds = 0;
minutes++;
}
h1.textContent = (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") + ":" + (seconds > 9 ? seconds : "0" + seconds);

timer();
}

function timer() {
t = setTimeout(add, 997.5);
}


/* Start button */
document.getElementById("start").onclick = timer;

/* Stop button */
document.getElementById("stop").onclick = function () {
clearTimeout(t);
}

/* Clear button */
document.getElementById("clear").onclick = function () {
h1.textContent = "00:00";
seconds = 0; minutes = 0;
clearTimeout(t);
}

所以是的,任何意见都会很棒。我尝试使停止函数(“clearTimeout(t)”)与计时器函数一起启动,只是为了看看是否会在启动之前重置它,但它不起作用。

有什么想法吗?你可能会看出我是新手。

最佳答案

我的建议是检查秒表是否在每次启动时启动。要么取消当前的一个,然后开始一个新的:

function timer() {
if (t) {
clearTimeout(t);
}
t = setTimeout(add, 997.5);
}

或者如果它已经启动,则不执行任何操作:

function timer() {
if (!t) {
t = setTimeout(add, 997.5);
}
}

document.getElementById("stop").onclick = function () {
clearTimeout(t);
t = null;
}

关于Javascript - 基本秒表可以多次启动,提高 watch 速度。解决方案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42972619/

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