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

标签 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 毫秒标记并发出警报“没时间了”?

最佳答案

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

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

关于javascript - 如何用另一个函数javascript停止计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30431590/

相关文章:

javascript - 如何在 jQuery 中提取当前 URL 和 ID?

javascript - 如何创建高级 html 测验

html - 最小宽度与最大宽度媒体查询 CSS

python - 在进程中每隔一段时间执行一次任务

javascript - 重置间隔计时器不起作用!怎么了?

javascript - 谷歌可视化-点击事件

javascript - 如何从多个元素添加和删除类?

android - 从 Google 相册上传多张照片

html - 无法加载 ttf 字体

java - 键盘 Action 监听器