Maximus Su
Maximus Su

Reputation: 35

How to restart a countdown timer that has set interval? Javascript

http://jsfiddle.net/Xotic750/wwg8H/

function startTimer(m, s) {
    timer.textContent = m + ":" + s;
    if (s == 0) {
        if (m == 0) {
            return;
        } else if (m != 0) {
            m = m - 1;
            s = 60;
        }
    }
    
    s = s - 1;
    id = setTimeout(function () {
        startTimer(m, s)
    }, 1000);
}

Refer to the link above, when you click start for one time, it countdown from 5:00 in a normal way. However, when you press the start button two times, the countdown is not normal? May i know how to tackle this problem? Thank you. If possible, please provide a codepen demo. Thank you

Upvotes: 0

Views: 188

Answers (3)

Jackiegrill
Jackiegrill

Reputation: 132

You need to clear the previous setInterval before you set a new one, use clearInterval(id).

Upvotes: 1

coderrr22
coderrr22

Reputation: 387

You should clear the timer on click before executing the timer.

Additional notes:

I recommend using different conditions so it will be less nested and more readable.

Notice there is a bug in your program you should reset the seconds to 59, not 60 - because the second already has passed.

This is a quick example :

let timerId;

function renderCountDownTimer(minutes, seconds) {
  timer.textContent = minutes + ":" + seconds;
  if(seconds==0 && minutes==0) {
    return;
  }
  if(seconds == 0){
    minutes--;
    seconds = 59;
  } else {
    seconds--;
  }
  timerId = setTimeout(() => {
    renderCountDownTimer(minutes,seconds)
  },1000)
}

start.addEventListener("click", function () {
    clearTimeout(timerId)
    renderCountDownTimer(5, 0);
}, false);

Added the fiddle :https://jsfiddle.net/fqdhaxz7/1/

Upvotes: 1

sssurii
sssurii

Reputation: 830

Clear previous timer when someone click on start button again.

start.addEventListener("click", function () {
   clearTimeout(id);
    startTimer(5, 0);
}, false);

Checkout updated fiddle: http://jsfiddle.net/Lthvxeda/1/

Upvotes: 2

Related Questions