javascript - 秒表 - 在单击启动计时器 onclick 处理程序之前将经过的时间保持为零
问题描述
秒表 - 在单击启动计时器 onclick 处理程序之前将经过的时间保持为零
嗨,我一直在为面试测试制作 Javascript 秒表。我有一个问题,即当浏览器加载时计时器会自动启动。我尝试编辑 add() 函数的“if”语句,但没有任何乐趣。谁能帮我?
var h1 = document.getElementsByTagName('h1')[0],
start = document.getElementById('start'),
stop = document.getElementById('stop'),
clear = document.getElementById('clear'),
milli = 0, seconds = 0, minutes = 0, hours = 0,
t;
function add() {
milli += 10;
if (milli >= 1000) {
milli = 0;
seconds++;
if (seconds >= 60) {
seconds = 0;
minutes++;
if (minutes >= 60) {
minutes = 0;
hours++;
}
}
}
h1.textContent = (hours ? (hours > 9 ? hours : "0" + hours) : "00") + ":" + (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") + ":" + (seconds > 9 ? seconds : "0" + seconds) + "." + (milli > 90 ? milli : "0" + milli);
timer();
}
function timer() {
t = setTimeout(add, 10);
}
timer();
/* Start button */
start.onclick = timer;
/* Stop button */
stop.onclick = function() {
clearTimeout(t);
}
/* Clear button */
clear.onclick = function() {
h1.textContent = "00:00:00:00";
milli = 0; seconds = 0; minutes = 0; hours = 0;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Test Stopwatch</title>
<link rel="stylesheet" href="assets/css/styles.css">
</head>
<body>
<section>
<h1>
<time>00:00:000:00</time>
</h1>
<button id="start">START</button>
<button id="stop">STOP</button>
<button id="clear">CLEAR</button>
</section>
<script src="assets/js/script.js"></script>
</body>
</html>
解决方案
您timer()
对 javascript 文件范围的根有一个调用,因此它会被自动调用。
function timer() {
t = setTimeout(add, 10);
}
timer(); // This starts it automatically. remove it.
正确的:
function timer() {
t = setTimeout(add, 10);
}
推荐阅读
- arrays - BigQuery 计算两个日期范围重叠
- c++ - 值如何存储在 unordered_map 中
- xml - 无法解析符号'@style/AppTheme.AppBarOverlay'
- input - 在 VSCode 中:为什么输入和输出交替显示,即使批量粘贴输入
- vue.js - Vue.js 以特定方式自动注册 Vuex 模块
- php - 从不同的表中查询另一列
- mysql - 无法将节点容器连接到 mysql(本地托管的 mysql)?
- abap - 如何获取最新的 MBEWH~LBKUM 值?
- c++ - 从字符串到整数的转换问题。(来自一对二维向量的字符串)
- powerapps - 我们如何在 Powerapps 中设置权限,使应用程序的创建者只能访问环境内的应用程序?