0

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; 
        } 
    }
}
2
  • try to change the 1000 Commented Aug 27, 2015 at 8:50
  • when you start again what is suppose to happen Commented Aug 27, 2015 at 8:52

2 Answers 2

4

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;
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.