Хотя ваш код работает, я хотел бы отметить пару вещей: добавление вашего обработчика паузы в ваш interval
не очень хорошая идея, вы будете добавлять обработчик паузы каждый интервал Таким образом, в итоге вы просто складываете количество функций, которые нужно обрабатывать при нажатии. Я сделал вашу кнопку переключаемой и разделил слушатель событий на функцию обработчика, чтобы вы могли прикрепить ее к любой кнопке. Эти изменения обеспечат бесперебойную работу вашего кода и облегчат его понимание:
function initCountdown() {
function event_click( event ){
// If our interval is null, we need to start the counter
// And also change the innerText so its obvious what the button will do next
if( interval === null ){
start();
event.target.innerText = 'pause';
} else {
pause();
event.target.innerText = 'start';
}
}
function start(){
// First use pause() to be sure all intervals are cleared
// it prevents them from doubling up
pause();
interval = setInterval( count, 1000 );
}
function pause() {
clearInterval( interval );
interval = null;
}
function count(){
// By doing this before declaring your variables
// you make it so the variables actually hold the new calculated values.
time[2]--;
if( time[2] == -1 ){
time[1]--;
time[2] = 59;
}
// Lets use some cool new syntax here to reduce the amount of code needed
// this will destructure an array assigning their indexed values to the index of the variable
var [ hours, minutes, seconds ] = time;
if( seconds == 0 && minutes == 0 && hours == 0 ){
clearInterval( interval );
}
// We always want to print something, and if the values are 0
// the output is still the same, so lets seperate that.
if (seconds < 10) {
outputElement.innerHTML = hours + ": " + minutes + ": " + "0" + seconds + " ";
} else {
outputElement.innerHTML = hours + ": " + minutes + ": " + seconds + " ";
}
}
// Lets also clearly name our things.
var outputElement = document.getElementById('demo');
var toggleElement = document.getElementById('toggle');
var interval = null;
var time = [10,10,10];
// Add event listener once
toggleElement.addEventListener( 'click', event_click );
toggleElement.click();
}
initCountdown();
<button id="toggle">start</button>
<div id="demo"></div>
Обновление Добавление кнопки отмены:
function initCountdown() {
function event_click_cancel( event ){
pause();
time = [ 0, 0, 0 ];
print();
}
function event_click_startpause( event ){
// If our interval is null, we need to start the counter
// And also change the innerText so its obvious what the button will do next
if( interval === null ){
start();
event.target.innerText = 'pause';
} else {
pause();
event.target.innerText = 'start';
}
}
function start(){
// First use pause() to be sure all intervals are cleared
// it prevents them from doubling up
pause();
interval = setInterval( count, 1000 );
}
function pause() {
clearInterval( interval );
interval = null;
}
function print(){
// I have separated out the print function as we want to use it
// in the count and the cancel function
var [ hours, minutes, seconds ] = time;
if( seconds == 0 && minutes == 0 && hours == 0 ){
clearInterval( interval );
}
if (seconds < 10) {
outputElement.innerHTML = hours + ": " + minutes + ": " + "0" + seconds + " ";
} else {
outputElement.innerHTML = hours + ": " + minutes + ": " + seconds + " ";
}
}
function count(){
// By doing this before declaring your variables
// you make it so the variables actually hold the new calculated values.
time[2]--;
if( time[2] == -1 ){
time[1]--;
time[2] = 59;
}
print();
}
// Lets also clearly name our things.
var outputElement = document.getElementById('demo');
var toggleElement = document.getElementById('toggle');
var cancelElement = document.getElementById('cancel');
var interval = null;
var time = [10,10,10];
// Add event listener once
toggleElement.addEventListener( 'click', event_click_startpause );
toggleElement.click();
cancelElement.addEventListener( 'click', event_click_cancel );
}
initCountdown();
<button id="toggle">start</button>
<button id="cancel">cancel</button>
<div id="demo"></div>