JavaScript clearInterval() Function

The clearInterval() function in javascript clears the interval which has been set by the setInterval() function before that.

Syntax:

clearInterval(nameOfInterval);

Parameters:

  • nameOfInterval: It is the name of the setInterval() function whose interval is to be cleared.

Example: In this example, we will write a function to clear the interval set by the setInterval() function using the clearInterval() function.

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
 
<body>
    <button id="btn" onclick="fun()" style="color: blue;">
        w3wiki</button>
    <button id="btn" onclick="stop()">Stop</button>
    <script>
        let t;
 
        function color() {
            if (document.getElementById('btn')
            .style.color == 'blue') {
                document.getElementById('btn')
                .style.color = 'green';
            } else {
                document.getElementById('btn')
                .style.color = 'blue';
            }
 
        }
 
        function fun() {
            t = setInterval(color, 1000);
 
        }
 
        function stop() {
            clearInterval(t);
        }
    </script>
</body>
 
</html>


Output: In this example, the w3wiki color changes and stays the same every second, after that it changes again. Click on Stop to clear the interval. 

Supported Browsers

  • Google Chrome 1.0
  • Edge 12.0
  • Internet Explorer 4.0
  • Firefox 1.0
  • Opera 4.0
  • Safari 1.0

We have a Cheat Sheet on Javascript where we covered all the important topics of Javascript to check those please go through Javascript Cheat Sheet-A Basic guide to JavaScript.



JavaScript clearTimeout() & clearInterval() Method

In JavaScript there are many inbuilt functions clearTimeout() and clearInterval() methods are some of them. when we use setTimeout() and setInterval() in any JavaScript program then it must clear the time used in those functions so we use the clearTimeout() and clearInterval() methods.

Similar Reads

Prerequisite:

setTimeout() and setInterval()...

JavaScript clearTimeout() Function

The clearTimeout() function in javascript clears the timeout which has been set by the setTimeout()function before that....

JavaScript clearInterval() Function

...