Q:

How to Stop setInterval() Call in JavaScript

0

How to Stop setInterval() Call in JavaScript

All Answers

need an explanation for this answer? contact us directly to get an explanation for this 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>

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to Trigger a Button Click on Enter Key Press i... >>
<< How to Remove Empty Elements from an Array in Java...