Vũ Nguyễn Duy
Vũ Nguyễn Duy

Reputation: 93

Javascript with count down timer

My problem is that the more I "click" on the Start time button, the faster it counts. How can I change it to normal 2 minute countdown timer? Like this: http://www.donothingfor2minutes.com/

My code:

var minute = 1; 
var second = 59; 
function time(){ 
    setInterval(starttime, 1000); 
}
function starttime(){ 
    document.getElementById("timer").innerHTML = minute +" : " + second ; 
    second--; 

    if(second == 00) { 
        minute--; 
        second = 59; 

        if (minute == 0) { 
            minute = 2; 
        } 
    }
}

Upvotes: 0

Views: 75

Answers (2)

Xavier Campenon
Xavier Campenon

Reputation: 91

If you want the timer to reset each time you click on the button, try resetting the interval on click:

var minute, second, timer;

function time() {
    clearInterval(timer);
    minute = 1;
    second = 59;
    timer = setInterval(updateTime, 1000);
}
function updateTime() {
    document.getElementById("timer").innerHTML = minute + " : " + second;
    second--;
    if (second == 00) {
        minute--;
        second = 59;
        if (minute == 0) {
            minute = 2;
        }
    }
}

Upvotes: 4

John Bupit
John Bupit

Reputation: 10618

What's happening is that you're probably calling time() multiple times, and thereby initiating multiple setInterval calls.
One way to avoid that would be to add a flag timeStarted, which starts the timer only when it is unset:

var minute = 1;
var second = 59;
var timeStarted = false;

function time() {
  if(!timeStarted) {
      timeStarted = true;
      setInterval(starttime, 1000);
  }
}

function starttime() {
  document.getElementById("timer").innerHTML = minute + " : " + second;
  second--;
  if (second == 00) {
    minute--;
    second = 59;
    if (minute == 0) {
      minute = 2;
    }
  }
}

Upvotes: 1

Related Questions