clearTimeout() not stopping setTimeout

tx291 picture tx291 · May 29, 2016 · Viewed 13.1k times · Source

I'm trying to build a really simple timer in Javascript (based on input from an HTML form), and my clearTimeout isn't working-- not even hitting the console.log that I have. In my HTML, to call the clearTimeout, I just have . I'm really not sure why this isn't working-- any help would be greatly appreciated! Thanks!

  function settimer(){

hour = document.getElementById('h').value;
minute = document.getElementById('m').value;
sec = document.getElementById('s').value;

hour = hour * 3600000;
minute = minute * 60000;
sec = sec * 1000;
totalTime = hour+minute+sec;

 var timer = setTimeout(function(){alert("Time's up"); }, totalTime);
 }

  function clear(){
    console.log("stopped")
    clearTimeout(timer);
  }

Answer

Richard Hamilton picture Richard Hamilton · May 29, 2016

You are declaring your timer variable inside a function, so it's scope is only local to that function. It cannot be called outside the function. To fix this, move the variable outside of your function.

A variable that is declared outside a function definition is a global variable, and its value is accessible and modifiable throughout your program.

A variable that is declared inside a function definition is local. It is created and destroyed every time the function is executed, and it cannot be accessed by any code outside the function.

Here's the documentation from Mozilla Developer Network

https://msdn.microsoft.com/library/bzt2dkta(v=vs.94).aspx

First declare the timer and total_time variables outside of any function, giving it local scope.

var timer;
var total_time;

Now, create the function to set the timer. Note that we want to use the var keyword to make these variables local to the scope.

function setTimer(){

    var hour = +(document.getElementById('h').value) * 3600000;
    var minute = +(document.getElementById('m').value) * 60000;
    var sec = +(document.getElementById('s').value) * 1000;

    totalTime = hour + minute + sec;    // Assign total time to variable
    alert("Time's up");
}

Assign the value of timer to setTimeout. We can now use the totalTime variable as the amount of time.

timer = setTimeout(setTimer, totalTime);

We can now stop the timer, because it has been given local scope.

function clear() {
    console.log("stopped")
    clearTimeout(timer);
}

It should work now. Try it again.