I am using the solution in this answer to create an accurate javascript timer. The code works fine. But I want it to have a fixed interval option. like it need to output 100, 200, 300, so on..,
Math.round(timer.getTime() / 1000);
this code rounds the value to the nearest second so timer goes 1, 2, 3, 4, 5...
I tried adjusting the duration of setInterval
to 50 and rounding to nearest 100, it works almost fine to my needs. but it is repeating numbers and sometimes skips few numbers.
And also I need some timer to start from a specific number, say from 400 to 10000. the class has 0 as default. How do I go about implementing that?
please find the codepen for more code and details: https://codepen.io/gurgoon32/pen/KKzYYKG
class Timer {
constructor() {
this.isRunning = false;
this.startTime = 0;
this.overallTime = 0;
}
_getTimeElapsedSinceLastStart() {
if (!this.startTime) {
return 0;
}
return Date.now() - this.startTime;
}
start() {
if (this.isRunning) {
return console.error('Timer is already running');
}
this.isRunning = true;
this.startTime = Date.now();
}
stop() {
if (!this.isRunning) {
return console.error('Timer is already stopped');
}
this.isRunning = false;
this.overallTime = this.overallTime + this._getTimeElapsedSinceLastStart();
}
reset() {
this.overallTime = 0;
if (this.isRunning) {
this.startTime = Date.now();
return;
}
this.startTime = 0;
}
getTime() {
if (!this.startTime) {
return 0;
}
if (this.isRunning) {
return this.overallTime + this._getTimeElapsedSinceLastStart();
}
return this.overallTime;
}
}
let the_interval;
function round_nearest_hundred(num) {
return Math.round(num / 100) * 100;
}
function onUpdateTimer(duration) {
const timeInSeconds = Math.round(timer.getTime() / 1000);
document.getElementById('time').innerText = timeInSeconds;
document.getElementById('accTime').innerText = round_nearest_hundred(timer.getTime());
console.log(round_nearest_hundred(timer.getTime()));
if (round_nearest_hundred(timer.getTime()) >= duration) {
document.getElementById('status').innerText = 'complete';
timer.stop();
timer_manager(false);
}
}
function timer_manager(flag, updateFunction, time, duration) {
if (flag) {
the_interval = setInterval(function() {
updateFunction(duration);
}, time);
} else {
clearInterval(the_interval);
}
}
const timer = new Timer();
//timer.start();
timer_manager(true, onUpdateTimer, 50, 10000);
document.getElementById('start').addEventListener('click', function() {
timer.start();
});
document.getElementById('stop').addEventListener('click', function() {
timer.stop();
});
document.getElementById('restart').addEventListener('click', function() {
timer_manager(true, onUpdateTimer, 100, 10000);
timer.reset();
timer.start();
});
<p>Elapsed time: <span id="time">0</span>s</p>
<p id="accTime"></p>
<p id="status"></p>
<button id="start">start</button>
<button id="stop">pause</button>
<button id="restart">restart</button>