JavaScript clearInterval method | clears the interval example code

JavaScript clearInterval method is used to clears the interval which has been set by setInterval() function before that. A setInterval() method is return id which will used as the parameter for the clearInterval() method.

Syntax

clearInterval(var)

Parameter Values

The id of the timer returned by the setInterval() method

Example of Javascript clearInterval() Method

setInterval() method execute the “myTimer” function once every 1 second and display it in p Tag. You can stop the timer by press the button, myStopFunction will call.

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

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

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

Output:

Example of Javascript clearInterval Method

How to clear all intervals javascript?

You could do like

var interval_id = window.setInterval("", 9999); // Get a reference to the last
                                                // interval +1
for (var i = 1; i < interval_id; i++)
        window.clearInterval(i);
//for clearing all intervals

Do comment if you have any questions and doubts 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.