如何使用另一个函数javascript来停止计时器 [英] how to stop timer with another function javascript

查看:107
本文介绍了如何使用另一个函数javascript来停止计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

()函数timer()
{
setTimeout(function()函数) {alert(Out of time)},3000); //警告3000毫秒后的超时
}
函数resetTime()
{
timer(); //这是不正确的,我认为它会覆盖第一个函数,但它只是增加了另一个计时器,这不是我想要的
}
function stopTime()
{
//这里有什么可以阻止第一个函数在3000毫秒之前完全执行并显示警告消息?

$ / code>

函数timer()在页面加载时启动,但如果我有一个按钮对于stopTime(),我点击它,我该如何阻止第一个函数的执行,并阻止它达到3000毫秒的标记,并提醒超时?

解决方案

使用一个范围覆盖所有函数的变量。

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


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

解决方案

Use a variable with scope over all of your functions.

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

这篇关于如何使用另一个函数javascript来停止计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆