-1

Why is clearInterval() not working? what am I doing wrong? I tried a bunch of things but they don't seem to work out...

var s = 60;
var timer = null;

function Ftimer (){
    document.getElementById("sec").innerHTML = s--;
}

document.getElementById("start").onclick = function () {
    var timer = setInterval(function(){ Ftimer() }, 1000);

}

document.getElementById("stop").onclick = function () {
    clearInterval(timer);
}
H Skee
  • 49
  • 2
  • 10
  • 1
    Debug your code. Place a breakpoint on the `clearInterval` line. Examine the value of `timer`. Then think real hard about why it's null. –  Dec 02 '16 at 18:08
  • `timer` is always `null`. You assign the return value of `setInterval` to a different, local, `timer` variable. – Quentin Dec 02 '16 at 18:08
  • remove `var` in your `onclick` function. – JulCh Dec 02 '16 at 18:09

2 Answers2

2

var timer makes the scope to the onclick function, not the global variable.

timer = setInterval(Ftimer, 1000);
epascarello
  • 204,599
  • 20
  • 195
  • 236
1

This is due to you overwriting your initial timer variable here:

document.getElementById("start").onclick = function () {
    // this clobbers your previous `timer` assignment
    var timer = setInterval(function(){ Ftimer() }, 1000);

}

So fix it by simply removing the var and use the outer scoped timer variable:

document.getElementById("start").onclick = function () {
    // this assigns to your previous `timer`
    timer = setInterval(function(){ Ftimer() }, 1000);

}
SonOfNun
  • 957
  • 7
  • 11