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"?
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'.
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.
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.
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);
Use a variable with scope over all of your functions.
var myTimer;
...
myTimer = setTimeout(...);
...
clearTimeout(myTimer);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With