I also found myself in need of something similar recently. To address this, I took the approach of creating an ES6 class to handle the functionality.
In my implementation, I utilized Events to communicate with other components regarding the timer state. Here is a fiddle that aligns with your requirements, although I've retained my EventManager() calls to showcase my actual process.
I made use of this particular EventManager. By default, the timer increments in 100ms intervals, but you have the flexibility to adjust this by invoking startTimer() with your desired interval value.
class Timer {
constructor(maxTime, startValue = 0) {
// Current timer value in tenths of a second
this.value = startValue;
// Maximum duration for the timer in seconds
this.maxTime = maxTime * 10;
this.timerRunning = false;
}
/**
* Initiates the timer. Increments the timer value every specified interval.
* @param {number} interval in ms
*/
startTimer(interval = 100) {
if (!this.timerRunning) {
let parent = this;
this.timerPointer = setInterval(function() {
if (parent.value < parent.maxTime) {
parent.value++;
//EventManager.fire('timerUpdated');
$("span").text(parent.value / 10 + "/" + parent.maxTime / 10);
} else {
parent.stopTimer();
//EventManager.fire('timeExceeded');
$("button").text("Start");
this.resetTimer();
$("span").text("Countdown over");
}
}, interval);
this.timerRunning = true;
}
}
// Halts the Timer.
stopTimer() {
clearInterval(this.timerPointer);
this.timerRunning = false;
}
// Resets the timer and stops it.
resetTimer() {
this.stopTimer();
this.value = 0;
$("span").text("0/" + this.maxTime/10);
//EventManager.fire('timerUpdated');
}
// Resets the timer and initiates from the beginning.
restartTimer() {
this.resetTimer();
this.startTimer();
}
}
let timer = new Timer(6);
$("#start-stop").click(function() {
if (timer.timerRunning) {
timer.stopTimer();
$("#start-stop").text("Start");
} else {
timer.startTimer();
$("#start-stop").text("Stop");
}
});
$("#reset").click(function() {
timer.resetTimer();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="start-stop">
Start
</button>
<button id="reset">
Reset
</button>
<span>Timer: </span>