how to stop timer with another function javascript

2019-06-23 15:41发布

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"?

3条回答
我只想做你的唯一
2楼-- · 2019-06-23 16:17

The value returned from setTimeout is a unique ID 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);
}
查看更多
贼婆χ
3楼-- · 2019-06-23 16:30
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

查看更多
\"骚年 ilove
4楼-- · 2019-06-23 16:36

Use a variable with scope over all of your functions.

var myTimer;
...
myTimer = setTimeout(...);
...
clearTimeout(myTimer);
查看更多
登录 后发表回答