Using clearTimeout()
to prevent the function to run:
Click the first button alert "Hello" after waiting 3 seconds.
<!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>