秒表不显示全部时间-缺少最后一位数字



我在这里有一个秒表,但它只显示11:11:10(0保持为零,1是一个变化(增加)的数字)。我该如何解决这个问题?

这是我的代码

var timer = document.getElementById('timer'); //Here is where I grab the html - no problems here 
var time = 0;
var running = 0;
document.body.onkeyup = function(e) {
if (e.keyCode == 32) {
timer.style.color = "white";
start();
}
}
function start() {
if (running == 0) {
reset();
running = 1;
increment();
} else {
running = 0;
}
}
function reset() {
running = 0;
time = 0;
timer.innerHTML = "00:00:00";
}
function increment() {
if (running == 1) {
setTimeout(function() {
time++;
var mins = Math.floor(time / 10 / 60);
if (mins <= 9) {
mins = "0" + mins;
}
var secs = Math.floor(time / 10);
if (secs <= 9) {
secs = "0" + secs;
}
var tenths = Math.floor(time % 10);
if (tenths <= 9) {
tenths = tenths;
}
//The hundredths part is experimental - I’m confused how to do it which is the whole question
var hundreths = Math.floor(time % 100);
timer.innerHTML = mins + ":" + secs + ":" + tenths + Math.floor(time / 1000 / 60);
increment();
}, 100);
}
}
<div id="timer">00:00:00</div>
<input type="button" value="Start" onclick="start()">
<input type="button" value="Reset" onclick="reset()">

完整的项目在这里,如果你想看它。我正在制作一个speedcube计时器:

https://speedcube-timer.coderguru.repl.co/

Thanks in advance

下面的代码修改为每百分之一秒运行一次,而不是每十分之一秒运行一次。

同时,它不会分别计算十分位数和百分位数,也能正确计算分钟(% 60)。

var timer = document.getElementById('timer'); //Here is where I grab the html - no problems here 
var time = 0;
var running = 0;
document.body.onkeyup = function(e) {
if (e.keyCode == 32) {
timer.style.color = "white";
start();
}
}
function start() {
if (running == 0) {
reset();
running = 1;
increment();
} else {
running = 0;
}
}
function reset() {
running = 0;
time = 0;
timer.innerHTML = "00:00.00";
}
function increment() {
if (running == 1) {
setTimeout(function() {
time++;
var mins = Math.floor(time / 100 / 60);
if (mins <= 9) {
mins = "0" + mins;
}
var secs = Math.floor(time / 100 % 60);
if (secs <= 9) {
secs = "0" + secs;
}

var hundredths = Math.floor(time % 100);
if (hundredths <= 9) {
hundredths = "0" + hundredths;
}

timer.innerHTML = mins + ":" + secs + "." + hundredths;
increment();
}, 10);
}
}
<div id="timer">00:00:00</div>
<input type="button" value="Start" onclick="start()">
<input type="button" value="Reset" onclick="reset()">

注意:这种计算时间的方法很幼稚。由于setIntervalsetTimeout调度回调的方式,您可能会看到相当数量的漂移(缓慢)。此外,如果另一个窗口/选项卡有焦点,浏览器可能不会运行回调。

修复这个问题将是另一个问题;0)

最新更新