如何用另一个函数javascript停止计时器

时间:2015-05-25 05:12:05

标签: javascript html timer timing

所以我有这个代码

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

函数timer()在页面加载时启动但是如果我有一个stopTime()按钮并且我点击它,我如何停止执行第一个函数并阻止它达到3000毫秒标记并提醒& #34;超时"?

3 个答案:

答案 0 :(得分:6)

使用范围超过所有功能的变量。

var myTimer;
...
myTimer = setTimeout(...);
...
clearTimeout(myTimer);

答案 1 :(得分:1)

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

试试这个会对你有用

答案 2 :(得分:-1)

setTimeout返回的值是一个唯一ID,您可以稍后使用该clearTimeout来取消超时。

var timeout;

function timer () {
    timeout = setTimeout(/* ... */);
}

function resetTime() {
    stopTime();
    timer();
}

function stopTime() {
    clearTimeout(timeout);
}