Online: 1026
                
            clearInterval in JavaScript is an native function, which is used to clear a timer set with the setInterval() method. The parameter of clearInterval() method is the ID value returned by the setInterval() method.
NOTE: We must use setInterval() method before using clearInterval() method in the script code.
Stop the current run time with the clearInterval() method.
<p>Click the below button to stop the current run time.</p> <p id="myId"></p> <input type="button" value="Stop" onclick="myStoptime()"/> <script> var myTime = setInterval(function () { myRuntime() }, 1000); function myRuntime() { var a = new Date(); var b = a.toLocaleTimeString(); document.getElementById("myId").innerHTML = b; } function myStoptime() { clearInterval(myTime); } </script>
In the above code, we set the current run timer with the setInterval() function {myRuntime()} and we are stopping the run time with the clearInterval() function. Onclick of the button "Stop" stops the current run time.
OUTPUT
<p>Click the button to stop changing the background color color.</p> <input type="button" value="Stop" onclick="fixColor()"/> <script> var a = setInterval(function () { myColor() }, 500); function myColor() { var b = document.body; b.style.backgroundColor = b.style.backgroundColor == "lightgreen" ? "lightblue" : "lightgreen"; } function fixColor() { clearInterval(a); } </script>
We are changing the background-color for every half second with the setInterval() method, and we stop the changing background-color with the clearInterval() method. Click here to see the output of the above code snippet.
<style>
        #myId{
        border:8px solid #0e0208;
        height:5px;
        width:90%;
        position:relative;
        background-color:yellow;
        }
        #myDemo {
        background-color:blue;
        height:100%;
        position:absolute;
        width:15px;
        }
</style>
<div id="myId">
<div id="myDemo"></div>
</div>
<br />
<br />
<br />
<input type="button" value="Start" onclick="myFunction()"/>
<script>
    function myFunction() {
        var a = document.getElementById("myDemo");
        var width = 0;
        var c = setInterval(Slide, 500);
        function Slide() {
            if (width == 150) {
                clearInterval(c);
            } else {
                width++;
                a.style.width = width + '%';
            }
        }
    }
</script>
We create a dynamic progress bar with the help of setInterval() function and clearInterval() function.
OUTPUT