javascript - javascript timer 每次重置和重新运行时都会将时间值加倍
问题描述
我正在启动一些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>
解决方案
该函数setInterval
不仅设置了一个超时事件,还设置了它们的重复时间表。
因此,正如评论中所指出的,每次您打电话时,cycle()
您都会创建一个额外的计时器计划,从而使它们在每个间隔有效地加倍。
要解决此问题,您需要更改为setTimeout
而不是 set Interval
,或者clearInterval
在您拨打新电话之前setInterval
拨打电话(或者什么都不做,因为setInterval
已经为您重复了)。该文档解释了所有这些功能:https ://javascript.info/settimeout-setinterval
推荐阅读
- node.js - 扩展请求类型以添加 Redis 客户端
- javascript - 任务从未定义:browserSync.reload
- python - 在变量中捕获在终端中运行的命令的输出
- docker - Docker 中的 PyTorch 只有在 root 时才能看到 GPU
- c# - 如何在没有硬编码(winforms)的情况下从现有的 .txt 文件中读取?
- php - PHP Session:ID 仅在服务器端生成?
- java - 如何用 /= 解决表达式
- node.js - 如何在 Sapper/Svelte 中打开和读取文件
- html - 一个 Excel 单元格中带有换行符的 HTML - 去掉一个额外的单元格空间
- log4j2 - 如何使用属性文件将多个相同类型的附加程序与一个记录器一起使用?