I am implementing a stopwatch by using Javascript. I have basic html document setup and a javascript file called stopwatch.js in which I have the following code. I make use of setInterval
function to execute the clockRunning
function every 1 second(1000ms). This gives me control over sec, min and hour to increment them accordingly, but I am having difficulty with inserting millisecond into the stopwatch. How should I increment the millisecond from 0 to 1000 and then reset to zero?
I have tried by decreasing the interval time for setInterval
function to be called every 1ms and then set millisecond
variable to time%1000
in which time
variable is increased by 1 every time the function is called. But it does not give the result I want. The millisecond
seems to be increasing way too slow.
var running = 0
var time = 0;
var hour = 0;
var min = 0;
var sec = 0;
var millisec = 0;
function start(){
started = window.setInterval(clockRunning, 1000);
}
function stop(){
window.clearInterval(started);
}
function clockRunning(){
time++;
sec++;
if (sec == 60){
min += 1;
sec = 0;
if (min == 60){
hour += 1;
min = 0;
}
}
document.getElementById(display-area).innerHTML = (hour ? (hour > 9 ? hour : 0 + hour) : 00)
+ : + (min ? (min > 9 ? min : 0 + min) : 00) + : + (sec > 9 ? sec : 0
+ sec);
};
<!DOCTYPE html>
<html>
<head>
<meta charset=UTF-8>
<title>Stopwatch</title>
<script src=stopwatch.js></script>
<style>
#display-area { font-size: 20pt; }
</style>
</head>
<body>
<div>
<output id=display-area>00:00:00.000</output>
</div>
<div>
<button id=toggle-button onClick=start()>Start</button>
<button id=toggle-button onClick=stop()>Stop</button>
<button id=reset-button>Reset</button>
</div>
</body>
</html>