我尝试将ms单位添加到此秒表并删除小时单位。有人可以向我展示如何做到这一点的例子吗? https://jsfiddle.net/pvk6p/
<h1><time>00:00:00</time></h1>
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();
答案 0 :(得分:0)
您可以尝试以下方法:
var h1 = document.getElementsByTagName('h1')[0],
start = document.getElementById('start'),
stop = document.getElementById('stop'),
clear = document.getElementById('clear'),
seconds = 0, minutes = 0, ms = 0,
t;
function add() {
ms++;
if (ms >= 100) {
ms = 0;
seconds++;
if (seconds >= 60) {
seconds = 0;
minutes++;
}
}
h1.textContent = (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00")
+ ":" + (seconds > 9 ? seconds : "0" + seconds)
+ ":" + (ms > 9 ? ms : "0" + ms);
// + ":" + (ms > 99 ? ms : (ms > 9 ? "0"+ms : "00" + ms));
//if you want to try to display every 1ms
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";
seconds = 0; minutes = 0; ms = 0;
}
jsfiddle:https://jsfiddle.net/pvk6p/5190/
如果您想尝试每1毫秒而不是10毫秒调用一次:
替换:
if (ms >= 100) {
的{{1}}
if (ms >= 1000) {
由+ ":" + (ms > 9 ? ms : "0" + ms);
+ ":" + (ms > 99 ? ms : (ms > 9 ? "0"+ms : "00" + ms));
由t = setTimeout(add, 10);
但是在我的PC上,这很慢,而且要比1ms多一点。