Reputation: 37
I have a stopwatch here, but it only displays 11:11:10 (0 staying as zero, and 1 being a changing(increasing) number). How can I fix this?
This is my Code:
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()">
The full project is here if you want to see it. I’m making a speedcube timer:
https://speedcube-timer.coderguru.repl.co/
Thanks in advance
Upvotes: 0
Views: 106
Reputation: 13060
Here's you code modified to run every 1 hundredth of a second rather than every tenth.
Also, it's not calculating tenths and hundredths separately and calculates the minutes correctly as well (% 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()">
NOTE:
This method of counting time is quite naive. Due to the way setInterval
and setTimeout
schedule the callback you're likely to see a fair amount of drift (slow) with this. Also, the browser is likely to not run the callback if another window/tab has focus.
Fixing that though would be a different question ;o)
Upvotes: 1