JSFiddle - React, Tailwind, and code Playground
HTML
<p id='timer'>0.00</p>
<p id='starter-container'>
<button type='button' id='starter'>Start</button>
<button type='button' id='starter-reset'>Reset</button>
</p>
CSS
html, body {
width: 100%;
height: 100%;
margin: 0;
padding; 0;
}
#timer {
font-size: 8em;
padding: 20px;
margin: 20px auto;
border: 1px solid black;
width: 3em;
text-align: center;
}
#starter-container {
text-align: center;
}
#starter-container button {
font-size: 2em;
}
JavaScript
var runs = 0,
max_runs = 10000,
speed = 10,
timeout = speed,
start_time = 0,
time = 0,
num_seconds = (30) * 1000,
mark_every = 100,
mark_next = time * speed,
timer_el = document.getElementById('timer'),
starter = document.getElementById('starter'),
reset = document.getElementById('starter-reset');
starter.addEventListener('click', function cl(){
reset_timer();
init_timer();
do_timer();
this.disabled = true;
});
reset.addEventListener('click', function cl(){
runs = max_runs++;
});
function init_timer() {
start_time = new Date().getTime();
time = Math.floor(start_time / speed);
}
function reset_timer() {
runs = 0;
starter.disabled = false;
timer_el.innerText = '0.00';
}
function do_timer(){
init_timer();
(function timer () {
var c_time = new Date().getTime(),
time_diff = c_time - start_time,
c_secs = 0;
runs += 1;
c_secs = (Math.round(time_diff / 10, 3) / 100).toString();
if (c_secs.indexOf('.') === -1) {
c_secs += '.00';
} else if (c_secs.split('.').pop().toString().length === 1 ) {
c_secs += '0';
}
timer_el.innerText = c_secs;
if (c_time >= mark_next) {
console.log(
'mark_next: ' + mark_next,
'mark time: ' + c_time,
'(' + (Math.floor(c_time * .01) * 100).toString().substring(10) + ')',
'precision: ' + (mark_next - c_time) + ')'
);
mark_next = Math.floor((c_time + mark_every) * .01) * 100;
}
if (Math.floor(c_time / speed) > time + 1) {
timeout = speed - ((c_time / speed) - time);
} else if (Math.floor(c_time / speed) < time + 1) {
timeout = speed + (time - Math.floor(c_time / speed));
} else {
timeout = speed;
}
...