How to Clear setInterval in JavaScript: Simple Guide
Use
clearInterval() with the ID returned by setInterval() to stop the repeated execution. Store the interval ID in a variable, then pass it to clearInterval() when you want to stop the interval.Syntax
The setInterval() function starts a repeated action and returns an ID. Use this ID with clearInterval() to stop it.
const intervalId = setInterval(callback, delay);- starts the interval and saves its ID.clearInterval(intervalId);- stops the interval using the saved ID.
javascript
const intervalId = setInterval(() => { console.log('Repeating every second'); }, 1000); // To stop the interval: clearInterval(intervalId);
Example
This example shows how to start a message repeating every second and then stop it after 5 seconds using clearInterval().
javascript
const intervalId = setInterval(() => { console.log('Hello every second'); }, 1000); setTimeout(() => { clearInterval(intervalId); console.log('Interval cleared'); }, 5000);
Output
Hello every second
Hello every second
Hello every second
Hello every second
Hello every second
Interval cleared
Common Pitfalls
One common mistake is not saving the interval ID returned by setInterval(). Without this ID, you cannot stop the interval. Another mistake is calling clearInterval() with a wrong or undefined ID, which will not stop the interval.
Always store the ID in a variable and use that variable to clear the interval.
javascript
/* Wrong way: not saving the ID */ setInterval(() => { console.log('This will never stop'); }, 1000); // Trying to clear without ID does nothing clearInterval(); /* Right way: save and clear */ const id = setInterval(() => { console.log('This will stop'); }, 1000); clearInterval(id);
Quick Reference
- setInterval(callback, delay): Starts repeating
callbackeverydelaymilliseconds. - clearInterval(intervalId): Stops the repeating action started by
setInterval. - Always save the ID returned by
setIntervalto clear it later.
Key Takeaways
Always save the ID returned by setInterval to clear it later.
Use clearInterval with the saved ID to stop the repeated action.
Not saving the interval ID makes it impossible to stop the interval.
clearInterval with a wrong or missing ID will not stop the interval.
Use setTimeout to schedule when to clear an interval if needed.