Definition:
It is used to stop a timer that is running with setInterval().
This will make the code stop running repeatedly.
If you change your mind, you can stop it with clearInterval().
It works like an alarm. You set the time, and it keeps ringing repeatedly.
If you no longer want it to ring, you turn off the switch.
Now you will clearly understand with the help of the flowchart.
Start | v Write your code insidesetInterval()| v Set the time delay | v Decide: Do you want the code to run? | |-- Yes --> Run thesetInterval()function | | | v | Wait for the given time | | | v | Code executes | | | v | End | |-- No --> UseclearInterval()to cancel the timer | v Timer is cancelled | v End
Syntax:
let timer = setInterval(function() {
// This code will run again and again.
}, time_in_milliseconds);
// To stop the timer
clearInterval(timer);
Example:
// This timer will show a message every 2 seconds
let timer = setInterval(function() {
console.log("The message is coming again and again!");
}, 2000);
// Stop the timer after 6 seconds
setTimeout(function() {
clearInterval(timer);
console.log("Timer stopped. The message will not come now.");
}, 6000);
Output:
The message is coming again and again! The message is coming again and again! Timer stopped. The message will not come now.
