首页 > 解决方案 > 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>

标签: javascript

解决方案


你可以看看这个小伙伴

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。
  • 除非没有替代方法,否则尽量避免使用全局范围变量。

推荐阅读