0

Code looks like that:

function startTimer(counter) {
    var interval = setInterval(function () {
        counter--;
        $('#timer').html(counter);
        // Display 'counter' wherever you want to display it.
        if (counter == 0) {
            clearInterval(interval);
            $('#question').html("Time ended");
            setTimeout(function () {
                window.location.href = "/";
            }, 5000);
            return false;
        }
    }, 1000);
}

What I want to do is, when I call this function multiple times, every time to reset timer to 30 seconds and kill all past instances. Currently it messes up with past intances when I call multiple times. What am I doing wrong?

heron
  • 3,611
  • 25
  • 80
  • 148

1 Answers1

0

You have to define the var interval outside the function:

   var interval;
    function startTimer(counter) {
        interval = setInterval(function () {
            counter--;
            $('#timer').html(counter);
            // Display 'counter' wherever you want to display it.
            if (counter == 0) {
                clearInterval(interval);
                $('#question').html("Time ended");
                setTimeout(function () {
                    window.location.href = "/";
                }, 5000);
                return false;
            }
        }, 1000);
    }
Chris Berlin
  • 744
  • 6
  • 15