gpt4 book ai didi

javascript - 秒表计时器无法正常工作

转载 作者:行者123 更新时间:2023-11-28 08:50:10 24 4
gpt4 key购买 nike

我是 JavaScript 初学者(PHP/C# 知识),我必须制作一个秒表。

现在我有一个问题;每次按下开始按钮时,计时器会走得更快,停止(暂停)按钮将停止工作。我似乎找不到合适的方法来修复它!

var display = document.getElementById("timer"),
start = document.getElementsByClassName("start"),
stop = document.getElementsByClassName("stop"),
seconds = 0,
minutes = 0,
hours = 0,
time;



start[0].addEventListener('click', startTimer);
stop[0].addEventListener('click', stopTimer);



function startTimer() {
timer();
time = setInterval( timer, 1000);

}

function stopTimer() {
clearInterval(time);
}


function timer(){
display.innerHTML = ExtraZero(hours)+":"+ExtraZero(minutes)+":"+ExtraZero(seconds);

seconds++;

if (seconds >= 60){
seconds = 0;
minutes++;

if (minutes >= 60){
minutes = 0;
hours ++;
}
}
}



function ExtraZero(i) {
if (i < 10)
{
i = "0" + i
}
return i
}
<!DOCTYPE html>
<html>
<head>
<title>Stopwatch</title>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
<body>


<div class="stopwatch">

<div class="timer">
<p id="timer">00:00:00</p>
</div>

<div class="start">
<button>START</button>
</div>

<div class="stop">
<button>STOP</button>
</div>

</div>




<script src="myscript.js" type="text/javascript"></script>

</body>
</html>

最佳答案

您不会在单击开始时检查计时器当前是否处于事件状态 - 只有在没有时才运行。因此,每次单击时,函数都会运行,而不管...因此您会看到它正在加速。

要补救,请将 time 初始和停止时设置为 null,然后在启动计时器时检查此状态。

var display = document.getElementById("timer"),
start = document.getElementsByClassName("start"),
stop = document.getElementsByClassName("stop"),
seconds = 0,
minutes = 0,
hours = 0,
time = null; /* <--- set to null initially, not necessarily needed but makes things clear */



start[0].addEventListener('click', startTimer);
stop[0].addEventListener('click', stopTimer);



function startTimer() {
if (time === null) { /* <--- only run the start function if the timer is not currently set */
timer();
time = setInterval(timer, 1000);
}

}

function stopTimer() {
clearInterval(time);
time = null; /* <-- exclicitely clean the timer variable */
}


function timer() {
display.innerHTML = ExtraZero(hours) + ":" + ExtraZero(minutes) + ":" + ExtraZero(seconds);

seconds++;

if (seconds >= 60) {
seconds = 0;
minutes++;

if (minutes >= 60) {
minutes = 0;
hours++;
}
}
}



function ExtraZero(i) {
if (i < 10) {
i = "0" + i
}
return i
}
<!DOCTYPE html>
<html>

<head>
<title>Stopwatch</title>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>

<body>


<div class="stopwatch">

<div class="timer">
<p id="timer">00:00:00</p>
</div>

<div class="start">
<button>START</button>
</div>

<div class="stop">
<button>STOP</button>
</div>

</div>




<script src="myscript.js" type="text/javascript"></script>

</body>

</html>

关于javascript - 秒表计时器无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27397165/

24 4 0
文章推荐: javascript - 如何将2个值存储到cookie中
文章推荐: css - 带有 的 SVG Sprite 图