1

Here is my code (that is inside a button.click() function)

if(inBreak === true) {
      inBreak = false;
      var timer = setInterval(function() {
        if(seconds == 0) {
          console.log(minutes);
          minutes -= 1;
          seconds = 59;
        } else {
          seconds -= 1;
        }
        $('.minutes').text(minutes);
        $('.seconds').text(seconds);
      }, 1000);
    } else {
      inBreak = true;
      console.log(timer);
      clearInterval(timer);
    }

The problem is clearInterval(timer) not working because timer isn't defined, but I defined it the first time I clicked (and used the function).

So do you have an idea for accomplish that ? I tried let / const instead var but not working anyway :(s

Bahman Parsa Manesh
  • 2,314
  • 3
  • 16
  • 32
Delbo ar
  • 362
  • 2
  • 4
  • 12
  • what do the `console.log(timer);` output ? – jonatjano Aug 29 '18 at 13:01
  • Possible duplicate of [How do JavaScript closures work?](https://stackoverflow.com/questions/111102/how-do-javascript-closures-work) – peeebeee Aug 29 '18 at 13:05
  • timer is only declared if inBreak is true, but cleared in the else condition so timer doesn't exist in the else condition. define timer where both conditions can access it. – digital-pollution Aug 29 '18 at 13:08

2 Answers2

4

timer is a local variable, it is destructed at the end of the function.

Store it somewhere else (as a global variable for instance) :

window.myTimer = setInterval(function() {
....

clearInterval(window.myTimer);
blue112
  • 52,634
  • 3
  • 45
  • 54
1

I suspect that you are declaring the timer variable inside the click handler and because of which on every click, variable timer is reset.

e.g.

function() { // event handler function
    var timer;
    if(inBreak === true) {
       // code
       timer = setInterval()
    } else {
        // code 
        console.log(timer);
    }
}

You should create a variable outside the event handler scope so that it is available and share same reference.

e.g.

var timer; // <- Move the declaration outside the function scope to be available and share same reference.
function() { // event handler function
    if(inBreak === true) {
       // code
       timer = setInterval()
    } else {
        // code 
        console.log(timer);
    }
}
Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59