-2

I have my setInterval function called on click, but after I clear it using an End Timer button it continues to run. It's a countdown clock so I want to make 2 buttons, a reset button and and end button. Both will pretty much do the same thing except end will make both minute and second values 0 and reset will make minute 25. I'm new to javascript so I assumed clearInterval() would terminate the setInterval() function and not allow it to be called until the corresponding button is clicked again.

var minCount = 25;          
var count = 60;

$("#begin").click(function timer(){
    var count = 60;
    minCount = minCount - 1;

    var counter = setInterval(function(){
        document.getElementById("min").innerHTML = minCount;
        count -= 1;
        document.getElementById("sec").innerHTML = count;

        if(count < 10){
            document.getElementById("sec").innerHTML = "0"+count;
            if(count == 0){
                clearInterval(counter);
                document.getElementById("min").innerHTML = minCount;
                document.getElementById("sec").innerHTML = count+"0";

                timer();
            }
        }
    },1000)
});

$("#end").click(function(){
    clearInterval(timer);
    document.getElementById("min").innerHTML = "00";
    document.getElementById("sec").innerHTML = "00";        
});
Ash
  • 2,108
  • 2
  • 17
  • 22

2 Answers2

1

Why do you call clearInterval(timer) ?

You need to pass the counter interval.

However, you are defining it on the "begin click" scope, and calling it on the "end click" scope wouldn 't work. Try extracting it to a common scope (say, after minCount and count) and use that on clearInterval.

Check this jsfiddle

Matheus208
  • 1,289
  • 2
  • 13
  • 26
1

You need to define the interval into a variable. See example below:

var minCount = 25;
var count = 60;
var counter;


$("#begin").click(function timer() {
    var count = 60;
    minCount = minCount - 1;

    counter = setInterval(function () {
        document.getElementById("min").innerHTML = minCount;
        count -= 1;
        document.getElementById("sec").innerHTML = count;

        if (count < 10) {
            document.getElementById("sec").innerHTML = "0" + count;
            if (count == 0) {
                clearInterval(counter);
                document.getElementById("min").innerHTML = minCount;
                document.getElementById("sec").innerHTML = count + "0";

                timer();
            }
        }

    }, 1000)
});


$("#end").click(function () {
    clearInterval(counter);
    document.getElementById("min").innerHTML = "00";
    document.getElementById("sec").innerHTML = "00";

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="begin">Begin</button>
<button id="end">End</button>
<div id="min">0</div>
<div id="sec">0</div>
ZarX
  • 1,096
  • 9
  • 17