I have a javascript function to countdown a timer. So I want to add pause option to this function. I tried this way,
function countdownTimeStart() {
var el = document.getElementById('demo');
var pause= document.getElementById('pause');
var time = [10,10,10];
var x = setInterval(function () {
var hours = time[0];
var minutes = time[1];
var seconds = time[2]--;
if (time[2] == -1) {
time[1]--;
time[2] = 59 }
function pauseTimer() {
savedTime = time;
clearInterval(x);
}
pause.addEventListener( 'click', pauseTimer);
if( seconds == 0 && minutes == 0 && hours == 0 ){
clearInterval(x);
el.innerHTML = "00:00:00";
} else if (seconds < 10) {
el.innerHTML = hours + ": " + minutes + ": " + "0" + seconds + " ";
} else {
el.innerHTML = hours + ": " + minutes + ": " + seconds + " ";
}
}, 1000);
}
countdownTimeStart();
<button id="pause" class="pause">Pause</button>
<div id="demo"></div>
The countdown timer working correctly. But the pause option not working. So how can I correct this script. Can someone help me.
Although your code is working, I would like to note a couple of things: adding your pause handler inside your
interval
isn't a good idea, you will be adding a pause handler every interval, so in the end you are just stacking up the amount of functions to handle when clicking. I have made your button toggle and separated out the event listener into a handler function so you can attach it to any button. These changes will keep your code working fluently while also making it easier to understand:Update Adding a cancel button: