Demons
Demons

Reputation: 179

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>

Upvotes: 1

Views: 1398

Answers (2)

Code Maniac
Code Maniac

Reputation: 37775

You can look at this mate

All you needed to do is define var ft in a scope which is accessible by both of the dontf and s funtion

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>

Suggestions

  • Use proper naming convention for the variables and functions which will make your code more readable and easy debugging.
  • Don't use var. use let or const.
  • Try avoid using global scope variables unless there is no alternate way.

Upvotes: 1

epascarello
epascarello

Reputation: 207557

The scope of ft is unreachable since it is defined inside of a function. Need to move it to a scope where the other method is able to reference it.

var ft;  // define it outside
function reset() {
  // var f = document.getElementById("ff").onclick; <<-- no clue what this is doing
  if (ft) window.clearTimeout(ft); // if it is running, remove it
  ft = setTimeout(dontf, 3000);
  // f = ft; <-- does not make sense
}

function dontf() {
  document.getElementById("r").src="H.jpg";
}

function s() {
  if (document.getElementById("r").src == "file:///C:/Users/S.jpg") {
    if (ft) clearTimeout(ft);
  }
}

Upvotes: 0

Related Questions