How to stop a timer using another javascript function

So I have this code

function timer() { setTimeout(function(){alert("Out of time")}, 3000); //Alerts "Out of time" after 3000 milliseconds } function resetTime() { timer(); //this is not right, i thought it would override the first function but it just adds another timer as well which is not what I want } function stopTime() { //What could go here to stop the first function from fully executing before it hits 3000 milliseconds and displays the alert message? } 

the timer () function starts when the page loads, but if I have a button for stopTime () and I click on it, how can I stop the first function and stop it from getting the 3000 millisecond mark and warn "Out of time"?

+5
source share
3 answers

Use a scope variable over all of your functions.

 var myTimer; ... myTimer = setTimeout(...); ... clearTimeout(myTimer); 
+6
source
 var timer; function timer() { timer = setTimeout(function(){alert("Out of time")}, 3000); //Alerts "Out of time" after 3000 milliseconds } function resetTime() { clearTimeout(timer); timer(); //this is not right, i thought it would override the first function but it just adds another timer as well which is not what I want } function stopTime() { //What could go here to stop the first function from fully executing before it hits 3000 milliseconds and displays the alert message? } 

try it, it will work for you

+1
source

The value returned with setTimeout is a unique identifier that you can use later to cancel the timeout with clearTimeout .

 var timeout; function timer () { timeout = setTimeout(/* ... */); } function resetTime() { stopTime(); timer(); } function stopTime() { clearTimeout(timeout); } 
-1
source

All Articles