JavaScript clearTimeout Method | Clear timeout Example code

JavaScript clearTimeout Method is used to clears the timeout which has been set by setTimeout() function before that. The setTimeout() method is return ID, which has to use in the clearTimeout() method as a parameter.

Syntax

clearTimeout(id_of_settimeout)

Parameter Values

Only ID value needed which returned by the setTimeout() method

Example of JavaScript clearTimeout() Method

Let’s see the example get the current time using setTimeout function, it will show time after 3 seconds.

If you pressed the stop button it will call the “myStopFunction” and Prevent the function set with the setTimeout() to execute:

<!DOCTYPE html> 
<html> 
  
<body> 
  
  
    <p id="demo"></p> 
    <button id="btn" onclick="myStopFunction()">Stop</button> 
  
    <script> 
        var myVar = setTimeout(myTimer, 3000);

	function myTimer() {
  		var d = new Date();
  		var t = d.toLocaleTimeString();
  		document.getElementById("demo").innerHTML = t;
		}

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

Output:

Example of JavaScript clearTimeout Method

Do comment if you have suggestion and questions on this tutorial.

Note: The All JS Examples codes are tested on the Safari browser (Version 12.0.2) and Chrome.
OS: macOS 10.14 Mojave
Code: HTML 5 Version


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.