Установите опцию паузы в сценарий таймера обратного отсчета Javascript - PullRequest
0 голосов
/ 01 мая 2018

Я создаю время обратного отсчета. Так что пока это мой код.

function countdownTimeStart() {

var el = document.getElementById('demo');
var cancel = document.getElementById('cancel');

/* Start count the time in timer panel */
var time = document.getElementById("picker-dates").value;
time = time.split(':');

var x = setInterval(function () {

    // set hours, minutes and seconds, decrease seconds
    var hours = time[0];
    var minutes = time[1];
    var seconds = time[2]--;

    console.log(time);

    // create a function to handle the cancel
    function cancelCountdown(){
        el.innerHTML = "00:00:00";
        clearInterval(x);
    }
    // attach listener to cancel if cancel button is clicked
    cancel.addEventListener( 'click', cancelCountdown);

    // if seconds are negative, set them to 59 and reduce minutes
    if (time[2] == -1) {
        time[1]--;
        time[2] = 59
    }

    // if minutes are negative, set them to 59 and reduce hours
    if (time[1] == -1) {
        time[0]--;
        time[1] = 59
    }

    // Output the result in an element with id="demo"
    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);}

Итак, я хочу создать для этого кнопку паузы. Я ссылался на подобные вопросы, такие как Javascript - Пауза setInterval () .

Кажется, что в jquery легко создать опцию паузы. Но я понятия не имею, как я могу применить это к моему сценарию. Может ли кто-нибудь помочь мне.

1 Ответ

0 голосов
/ 01 мая 2018

Нажав на паузу, вы можете создать объект типа savedTime, который сохраняет текущее значение массива time. Затем, когда нажата start, вы можете проверить, есть ли что-нибудь в savedTime. Если это так, тогда присвойте hours, minutes и seconds значение этого объекта; в противном случае установите их значения по умолчанию из входных данных. Например, что-то вроде:

var el = document.getElementById('demo');
var cancel = document.getElementById('cancel');
var savedTime;
function countdownTimeStart() {
  /* Start count the time in timer panel */
  var timeValue = document.getElementById("picker-dates").value;
  var time;
  if (savedTime) {
    time = savedTime;
    savedTime = null;
  } else time = timeValue.split(':');

  var x = setInterval(function () {
    // set hours, minutes and seconds, decrease seconds
    var hours = time[0];
    var minutes = time[1];
    var seconds = time[2]--;

    // rest of countdownTimeStart is as normal
    // ...
  });

  // Attach this function to your pause button:
  function pauseTimer() {
    savedTime = time;
    clearInterval(x);
  }
}
...