-1
var started = false;
function start() {
    var timer;
    if(started === false) {
        timer = setInterval(decrease, 1000);
        started = true;
    } else {
        clearInterval(timer);
        console.log("Should Clear");
    }
}

The setInterval works but when I run the function again, it prints in the console that it should be removed. But it doesn't.

Ahmed Nezar
  • 77
  • 1
  • 10

4 Answers4

2

timer is declared inside your function, so when you call it again, it's a new instance.

Try declaring it outside the function, like this:

var started = false;
var timer;
function start() {
    if(started === false) {
        timer = setInterval(decrease, 1000);
        started = true;
    } else {
        clearInterval(timer);
        console.log("Should Clear");
    }
}
augustomen
  • 8,977
  • 3
  • 43
  • 63
1

timer gets reinitialized every time you call start so the second time you call it, it's not pointing to a timer id to clear.

zzzzBov
  • 174,988
  • 54
  • 320
  • 367
1

use like this

var started = false;
var timer;
function start() {

    if(started === false) {
        timer = setInterval(decrease, 1000);
        started = true;
    } else {
        clearInterval(timer);
        console.log("Should Clear");
    }
}
Arjun Bala
  • 287
  • 1
  • 8
0

Because timer is in the scope of the function. So when you call it the second time, it is in another scope.

Mathieu Gemard
  • 514
  • 7
  • 11