0

I've got issue with stopping setInterval timer. I know It should stop after using claeerInterval, but in my case something wrong.

This is part of code what I have:

    function startTimer(duration, display) {
        var timer = duration, minutes, seconds;
        var tmr = setInterval(function () {
            minutes = parseInt(timer / 60, 10)
            seconds = parseInt(timer % 60, 10);

            minutes = minutes < 10 ? "0" + minutes : minutes;
            seconds = seconds < 10 ? "0" + seconds : seconds;

            display.textContent = minutes + ":" + seconds;

            if (--timer < 0) {
                timer = duration;
            }
        }, 1000);
    }

    function beginTimer() {
        var fiveMinutes = 60 * 5,
        display = document.querySelector('#time');
        startTimer(fiveMinutes, display);
    }

    function gameOver() {
        // some more code
        clearInterval(tmr); // there throws an error
    }

And after It I got an error:

Uncaught ReferenceError: tmr is not defined

Have you ideas what's wrong with It? should I make It public or something else?

Infinity
  • 828
  • 4
  • 15
  • 41
  • 1
    variable `tmr` is not visible in scope of `gameOver`. Yes, you should declare it as a variable visible to both functions – Kirill Slatin Nov 17 '16 at 17:46
  • @KirillSlatin thank you for reply, but how to solve It? how could I make It visible? – Infinity Nov 17 '16 at 17:47
  • 1
    Declare it as a global variable outside the functions. – Barmar Nov 17 '16 at 17:47
  • Outside the functions put `var tmr;`. Inside `startTimer` you'll have `tmr = setInterval(function () {....` – Matt Burland Nov 17 '16 at 17:48
  • For example, `var tmr; function startTimer(...) { tmr = setTimeout ... }` Please not there is no `var` before assigning `tmr` anymore – Kirill Slatin Nov 17 '16 at 17:48
  • Thank you guys, for pretty simple solution, I've tried before `var tmr;` outside the functions, but I missed to remove `var` from `startTimer()` function.... Thank you very much! – Infinity Nov 17 '16 at 17:52

0 Answers0