WEB TUTORIALS
PRACTICE EXAMPLES
HTML REFERENCES
CSS REFERENCES
PHP REFERENCES

How to Stop setInterval() Call in JavaScript

Topic: JavaScript / jQueryPrev|Next

Answer: Use the clearInterval() Method

The setInterval() method returns an interval ID which uniquely identifies the interval. You can pass this interval ID to the global clearInterval() method to cancel or stop setInterval() call.

Let's try out the following example to understand how it basically works:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Stop setInterval() Call</title>
</head>
<body>
    <p>Press start/stop button to start/stop setInterval() call.</p>
    <button type="button" id="startBtn">Start</button>
    <button type="button" id="stopBtn">Stop</button>
    <div id="myDiv"></div>

    <script>
    var intervalID;

    // Function to call repeatedly 
    function sayHello(){
        document.getElementById("myDiv").innerHTML += '<p>Hello World!</p>';
    }
    
    // Function to start setInterval call
    function start(){
        intervalID = setInterval(sayHello, 1000);
    }

    // Function to stop setInterval call
    function stop(){
        clearInterval(intervalID);
    }

    document.getElementById("startBtn").addEventListener("click", start);
    document.getElementById("stopBtn").addEventListener("click", stop);
    </script>
</body>
</html>

Related FAQ

Here are some more FAQ related to this topic:

Bootstrap UI Design Templates Property Marvels - A Leading Real Estate Portal for Premium Properties