javascript - How to ClearTimeout of a function in JavaScript?
问题描述
I have a function that will continuously reset every time a button is clicked, however, I am trying to clear that timer when a certain picture is on the screen. There are more things going on in the program but this is the general problem I am having. Here is what I have so far:
JavaScript:
function reset() {
var f = document.getElementById("ff").onclick;
var ft = setTimeout(function(){ dontf() }, 3000);
f = ft;
}
function dontf() {
document.getElementById("r").src="H.jpg";
}
function s() {
if (document.getElementById("r").src == "file:///C:/Users/S.jpg") {
clearTimeout(ft);
}
}
HTML
<button onclick="reset(); s();" id="ff">Fd</button>
解决方案
你可以看看这个小伙伴
dontf
您需要做的就是在一个可以被 the和s
函数访问的范围内定义 var ft
let timer;
function reset() {
const element = document.getElementById("resetButton");
timer = setTimeout(function(){ addImageFunc() }, 3000);
}
function addImageFunc() {
console.log(timer); document.getElementById("addImage").src="https://images.pexels.com/photos/248797/pexels-photo-248797.jpeg?auto=compress&cs=tinysrgb&h=350";
}
function stopReset() {
if (document.getElementById("addImage").src == "https://images.pexels.com/photos/248797/pexels-photo-248797.jpeg?auto=compress&cs=tinysrgb&h=350") {
clearTimeout(timer);
}
}
<html>
<body>
<button onclick="reset(); stopReset();" id="resetButton">Fd</button>
<img id='addImage'>
</body>
</html>
建议
- 对变量和函数使用正确的命名约定,这将使您的代码更具可读性和易于调试。
- 不要使用 var。使用 let 或 const。
- 除非没有替代方法,否则尽量避免使用全局范围变量。
推荐阅读
- java - 为什么打印 char[] 数组不打印任何输出?
- delphi - 将组件定义为具有与其 ClassName 不同的名称前缀(减去“T”)
- sql-server - SQL Server 中多个小数点的数据类型
- java - 提高使用多个微服务填充材料爆炸树的性能的方法
- mongodb - 如何在猫鼬中插入自动增量编号
- html - html/css 或 boostrap 中的导航搜索栏
- c# - 如何在.net中设置可变时间秒精度格式?
- java - Gmail API,撤销后获取新的访问令牌
- r - 具有函数的数据框的输出元素(在 R 环境中)
- ios - ITMS-90809:当我使用 react-native-webview 时不推荐使用 API