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
Contact Us