2
votes

I've made a timer with setInterval():

var seconds = 0, minutes = 0;
var timer = document.querySelector("#timer");
var interval = null;
function beginTimer() {
    var interval = setInterval(function(){
        timer.innerHTML = minutes + " Minute(s) " + seconds + "     Seconds";
        seconds++;
        if(seconds == 60) {
            minutes++;
            seconds = 0;
        }
        else if(minutes == 60) {
            return "Out of time!";          
        }
    }, 1000);
}

I've set a button in HTML to reset it, but when I use it to clear the timer, it continues running. This is the function with the clearInterval() in it.

function beginGame() {
cards = shuffle(cards);
for (var n = 0; n < cards.length; n++) {
    allCards.innerHTML = "";
    [].forEach.call(cards, function(item) {
        allCards.appendChild(item);
    });
    cards[n].classList.remove("match", "open", "disable", "show");
}
    //resetting values
    moves = 0;
    counter.innerHTML = moves;
    star1.style.visibility = "visible";
    star2.style.visibility = "visible";
    star3.style.visibility = "visible";
    lemon.style.visibility = "hidden";

    seconds = 0;
    minutes = 0;
    clearInterval(interval);
    var timer = document.querySelector("#timer");
    timer.innerHTML = "0 Minute(s) 0 Seconds";
}

I've been researching this for a couple of days with no luck... could someone kindly help me understand how to stop the timer from continuing to run after reset is initialized? Thanks.

3
Inside of beginTimer(), remove the var in front of interval. That causes it to create a local variable in the function's scope, rather than referencing the one in the parent scope. - Patrick Roberts
You make it sound so easy. Thank you so much. :) - Eric Phifer

3 Answers

4
votes

Because you have var interval inside beginTimer, the interval variable inside beginTimer will always reference the local variable, which is distinct from the outer interval (which is never touched). Once beginTimer ends, the local interval variable will simply be garbage collected. Leave off the var to assign to the outer variable instead:

var interval = null;
function beginTimer() {
  interval = setInterval(function(){
0
votes

var intervalinside the beginTimer() is error.

var seconds = 0, minutes = 0;
var timer = document.querySelector("#timer");
var interval = null;
function beginTimer() {
   // var interval = setInterval(function(){
   interval = setInterval(function(){
    timer.innerHTML = minutes + " Minute(s) " + seconds + "     Seconds";
    seconds++;
    if(seconds == 60) {
        minutes++;
        seconds = 0;
    }
    else if(minutes == 60) {
        return "Out of time!";          
    }
   }, 1000);
}
0
votes

You need also to reset the ongoing timer before starting a new one. Please try the following:

var interval;
function beginTimer() {
  clearInterval(interval);
  interval = setInterval(function(){
...