How to use clearInterval() method In Javascript

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

Syntax:

clearInterval(nameOfInterval);

Example: Here, Clicking the “Start Script” button initiates a repeating action every second using setInterval(). Clicking the “Stop Script” button stops the repeating action by calling clearInterval(intervalId), where intervalId is the ID returned by setInterval(). The script logs “Repeating action…” to the console every second until you click “Stop Script,” at which point it logs “Script stopped.”

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0">
    <title>Script Termination Example</title>
</head>
 
<body>
 
    <button id="startButton">Start Script</button>
    <button id="stopButton">Stop Script</button>
 
    <script>
        let intervalId; // Variable to store the interval ID
 
        function repeatingAction() {
            console.log("Repeating action...");
        }
 
        document.getElementById("startButton")
              .addEventListener("click", function () {
            // Start the repeating action every 1 second
            intervalId = setInterval(repeatingAction, 1000);
        });
 
        document.getElementById("stopButton")
            .addEventListener("click", function () {
             
              // Stop the repeating action when the "Stop Script"
            // button is clicked
            clearInterval(intervalId);
            console.log("Script stopped.");
        });
    </script>
</body>
 
</html>


Output:



How to terminate a script in JavaScript ?

To terminate a script in JavaScript, we have different approaches:

Table of Content

  • Using return
  • Terminating a part of the Script
  • Throwing an error on purpose
  • Using process.exit for Node.JS applications
  • Using clearInterval() method

Similar Reads

Method 1: Using return

In order to terminate a section of the script, a return statement can be included within that specific scope....

Method 2: Terminating a part of the Script

...

Method 3: Throwing an error on purpose

Example: Depending on a condition, a certain section of the script can be terminated using a “return” statement. The “return ” statement returns “undefined” to the immediate parent scope, where the termination can be handled. This is the best practice since handling terminations makes it easier for future debugging and readability of the code....

Method 4: Using process.exit for Node.JS applications

...

Method 5: Using clearInterval() method

Example: We deliberately throw an error to terminate the section of the script that we want to. It is best practice to handle the error using a “try-catch” block....

Contact Us