Chathuri Fernando
Chathuri Fernando

Reputation: 972

Set Pause option to Javascript Countdown Timer script

I'am creating a countdown timer.So this is the my code so far.

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);}

So I want to create a pause button for this. I refered similar questions such as Javascript - Pausing setInterval().

It seems that it is easy to create pause option in jquery. But I haven't idea how can I apply this to my script. Can someone help me.

Upvotes: 2

Views: 417

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370689

On pause click, you could create an object like savedTime that saves the current value of the time array. Then, when start is clicked, you could check to see if there is anything in savedTime. If so, then assign hours, minutes, and seconds to the value of that object; otherwise, set their values to the default ones from the input. For example, something like:

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);
  }
}

Upvotes: 1

Related Questions