I'm creating a stopwatch with setInterval like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Stopwatch</title>
<link href="https://fonts.googleapis.com/css?family=Saira" rel="stylesheet">
<link href="stopwatch.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Droid+Sans" rel="stylesheet">
</head>
<body>
<div class="but">
<h1>Stopwatch</h1>
<p id="timer">0</p>
<button id="start">Start/Stop</button>
<button id="reset">Reset</button>
<button id="record">Record Time</button>
</div>
<script src="stopwatch.js"></script>
</body>
</html>
and the JavaScript file:
var timer = document.getElementById("timer");
var sec = 0;
var on = false;
var interval;
//execution
document.getElementById("start").addEventListener("click", startStop);
//function
function startStop(){
if(on == false){
counter();
on = true;
}else if(on == true){
clearInterval(interval);
on = false;
}
}
function counter(){
interval = setInterval(time, 1000);
}
function time(){
sec += 0.01;
timer.innerHTML = sec;
}
I set the interval at 1000 to test it. It worked well at the first 5 seconds, but at the 6th second, the number shown was 0.060000000000000005, and the 9th, 10th, 11th didn't work as well. Can anybody help me fix this problem please?