Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to stop timer with another function javascript

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 function timer() starts as the page loads but if I have a button for stopTime() and I click on it, how do I stop the first function from executing and stop it from hitting the 3000 millisecond mark and alerting "Out of time"?

like image 269
user3450498 Avatar asked May 25 '15 05:05

user3450498


People also ask

How do you stop a timer in JavaScript?

Clicking the Stop button clears the timer by using the clearInterval(), passing in the 'check' variable that is returned by the call to setInterval(). The last step is to reset the value of the counter to '0'.

How do you stop a setTimeout?

To cancel a setTimeout() method from running, you need to use the clearTimeout() method, passing the ID value returned when you call the setTimeout() method.

Does clearTimeout stop execution?

So the code reaches clearTimeout and executes before the timeout is done. Yes, in your code the call to clearTimeout() will happen before the timer fires. Timeouts do not interrupt code that's running synchronously like your "long" function.

How do I create a timeout in JavaScript?

The setTimeout() method executes a block of code after the specified time. The method executes the code only once. The commonly used syntax of JavaScript setTimeout is: setTimeout(function, milliseconds);


2 Answers

Use a variable with scope over all of your functions.

var myTimer;
...
myTimer = setTimeout(...);
...
clearTimeout(myTimer);
like image 199
Amadan Avatar answered Oct 12 '22 06:10

Amadan


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 this it will Work For you

like image 34
Junaid Ahmed Avatar answered Oct 12 '22 06:10

Junaid Ahmed