我已经有一段时间了。每当我点击"开始"不止一次,它加起来。如果你注意到,如果我点击"开始"两次,我的时钟计数开始变得有趣:
var h1 = document.getElementsByTagName('h1')[0],
start = document.getElementById('start'),
stop = document.getElementById('stop'),
clear = document.getElementById('clear'),
seconds = 0,
minutes = 0,
GG;
function add() {
seconds++;
if (seconds >= 60) {
seconds = 0;
minutes++;
if (minutes >= 60) {
minutes = 0;
}
}
h1.textContent =
(minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") +
":" + (seconds > 9 ? seconds : "0" + seconds);
timer();
}
function timer() {
GG = setTimeout(add, 1000);
}
timer();
start.onclick = timer;
stop.onclick = function() {
clearTimeout(GG);
}
clear.onclick = function() {
h1.textContent = "00:00";
seconds = 0;
minutes = 0;
}

<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div class="time-container">
<h1><time>00:00</time></h1>
<button id="start">start</button>
<button id="stop">stop</button>
<button id="clear">clear</button>
</div>
</body>
</html>
&#13;
我必须按STOP,N是START的N倍。 如果我想解决这个问题,那么任何成功的按下START都无关紧要。任何时候都只会运行一次计数执行。
答案 0 :(得分:0)
添加变量以检查点击start
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div class="time-container">
<h1><time>00:00</time></h1>
<button id="start">start</button>
<button id="stop">stop</button>
<button id="clear">clear</button>
</div>
</body>
<script>
var h1 = document.getElementsByTagName('h1')[0]
, start = document.getElementById('start')
, stop = document.getElementById('stop')
, clear = document.getElementById('clear')
, seconds = 0
, minutes = 0
, GG
, flag = true;
function add() {
seconds++;
if (seconds >= 60) {
seconds = 0;
minutes++;
if (minutes >= 60) {
minutes = 0;
}
}
h1.textContent = (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") + ":" + (seconds > 9 ? seconds : "0" + seconds);
timer();
}
function timer() {
GG = setTimeout(add, 1000);
}
start.onclick = function () {
if(flag)
{
timer();
flag = false;
}
}
stop.onclick = function () {
clearTimeout(GG);
flag = true;
}
clear.onclick = function () {
h1.textContent = "00:00";
seconds = 0;
minutes = 0;
}
</script>
</html>
&#13;