Javascript Browser Window setTimeout() Method stop by clearTimeout()

Introduction

Using clearTimeout() to prevent the function to run:

Click the first button alert "Hello" after waiting 3 seconds.

View in separate window

<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Test</button>
<button onclick="myStopFunction()">Stop the alert</button>
<script>
var myVar;//from  w  w  w  .  jav  a 2 s .c om

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

function myStopFunction() {
  clearTimeout(myVar);
}
</script>

</body>
</html>



PreviousNext

Related