【发布时间】:2020-02-04 15:59:37
【问题描述】:
我使用 HTML 和 Javascript 为秒表创建了一个脚本。我让它以小时分钟和秒为单位工作。我还有停止-启动计时器、停止计时器和清除计时器的功能。
谁能帮我在秒表脚本中添加毫秒?
到目前为止,这是我的代码:
var h1 = document.getElementsByTagName('h1')[0],
start = document.getElementById('start'),
stop = document.getElementById('stop'),
clear = document.getElementById('clear'),
seconds = 0, minutes = 0, hours = 0,
t;
function add() {
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);
timer();
}
function timer() {
t = setTimeout(add, 1000);
}
timer();
/* Start button */
start.onclick = timer;
/* Stop button */
stop.onclick = function() {
clearTimeout(t);
}
/* Clear button */
clear.onclick = function() {
h1.textContent = "00:00:00";
seconds = 0; minutes = 0; hours = 0;
}
<h1><time>00:00:00</time></h1>
<button id="start">start</button>
<button id="stop">stop</button>
<button id="clear">clear</button>
【问题讨论】:
-
如果您依赖于每秒准确调用的超时函数,它不会很准确。最好的办法是使用超时来更新显示并使用几个日期对象来准确跟踪经过的时间。
标签: javascript html