【发布时间】:2021-04-21 02:14:06
【问题描述】:
我正在启动一些 javascript 项目,但我发现这个计时器有些困难 第一个问题是停止按钮不起作用,我尝试了很多代码但没有任何效果 然后每次我点击重置而不是从 1 到 2 到 3 时它会变为 1 然后 2和4然后是8等等 我试着用间隔看,但第一次它是正确的 所以我检查了重置功能
var timer = document.querySelector("#timer");
var start = document.querySelector("#start");
var pause = document.querySelector("#stop");
var stop = document.querySelector("#stop");
var time_stopped = true;
var hours = 0;
var minutes = 0;
var seconds = 0;
function start_timer() {
if (time_stopped == true){
time_stopped = false;
cycle();
}
console.log("timer started!");
pause.style.display = "unset";
}
function stop_timer() {
if (stop_timer == false) {
stop_timer = true;
}
console.log("time stopped!");
pause.style.display = "none";
}
function restart_timer() {
timer.innerHTML = "00 00 00";
hours = 0;
minutes = 0;
seconds = 0;
time_stopped = true;
cycle();
}
function cycle() {
if (time_stopped == false) {
hours = parseInt(hours);
minutes = parseInt(minutes);
seconds = parseInt(seconds);
seconds = seconds + 1;
if (seconds == 60) {
minutes += 1;
seconds = 0;
}
if (minutes == 60) {
hours += 1;
minutes = 0;
}
if (seconds < 10 || seconds == 0) {
seconds = "0" + seconds;
}
if (minutes < 10 || minutes == 0) {
minutes = "0" + minutes;
}
if (hours < 10 || hours == 0) {
hours = "0" + hours;
}
timer.innerHTML = `${hours}:${minutes}:${seconds}`;
setInterval(cycle,1000);
}
}
这是html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>stopwatch (timer)</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div>
<div id="timer">
00:00:00
</div>
<ul>
<button id="start" onclick="start_timer()">start</button>
<button id="stop" onclick="stop_timer()">stop</button>
<button id="restart" onclick="restart_timer()">restart</button>
</ul>
</div>
<script src="script.js"></script>
</body>
</html>
【问题讨论】:
-
仅供参考,setTimeout 不准确,所以加 1 会在一段时间后关闭。
-
每次调用循环时,您都会创建另一个区间......区间1会创建区间2。 interval1创建interval3,interval2创建interval4,interval1创建interval5,interval2创建interval6,interval3创建interval7,interval4创建interval8......
-
我把它们都删了,还是一样的问题,但是我应该用什么来代替 setInterval?
-
你应该只创建一个区间......你不应该在循环中创建一个区间......
-
非常感谢您的帮助
标签: javascript css function web