0

I have a function with a setTimeout method. I want to stop it if the user executes another function (prevent "Alert" from happening). Is that possible?

function myFunction() {
    setTimeout(function(){ alert("Hello"); }, 3000);
}
function stopThis() {
    //how to stop myFunction()?
}
<p>Click the button to wait 3 seconds, then alert "Hello".</p>
<button onclick="myFunction()">Activate</button>
<button onclick="stopThis()">Stop it</button>

2 Answers2

2

You can use clearTimeout function

var myVar;

function myFunction() {
    myVar = setTimeout(function(){ alert("Hello"); }, 3000);
}

function myStopFunction() {
    clearTimeout(myVar);
}
suvroc
  • 3,058
  • 1
  • 15
  • 29
1

Yes, you'll have to store the return value of setTimeout and then clear it:

var timeout = setTimeout(..);

..

clearTimeout(timeout);
deceze
  • 510,633
  • 85
  • 743
  • 889