JSFiddle - React, Tailwind, and code Playground
by octatone
HTML
<div id="timer">
</div>
JavaScript
var Timer = {
start_time: null,
id: null,
callback: null,
msToDuration: function(dur){
var dur_s = dur / 1000;
var hours = Math.floor(dur_s / 3600);
var minutes = Math.floor((dur_s % 3600) / 60);
var seconds = Math.floor((dur_s % 3600) % 60);
var str = '';
str += (hours > 0) ? hours + ':' : '0:';
str += (minutes > 0) ? (minutes < 10 ? '0' + minutes + ':' : minutes + ':') : '00:';
str += (seconds > 0) ? (seconds < 10 ? '0' + seconds : seconds) : '00';
return str;
},
start: function(callback){
this.stop();
this.callback = callback;
this.start_time = new Date();// - 3540000; test hour roll over
this.id = setInterval(Timer.run, 1000);
},
stop: function(){
if(this.id){
clearInterval(this.id);
}
},
run: function(){
var now = new Date();
Timer.callback(Timer.msToDuration(now - Timer.start_time));
}
};
Timer.start(function(str){
$('#timer').html(str);
});