Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How do I clear the usage of setInterval()?
The setInterval() method executes a function repeatedly at specified intervals. Unlike setTimeout() which runs once, setInterval() continues indefinitely until cleared.
Syntax
let intervalId = setInterval(function, delay);
Example: Basic setInterval Usage
let count = 0;
let intervalId = setInterval(function() {
count++;
console.log("Hello " + count);
// Stop after 3 executions
if (count === 3) {
clearInterval(intervalId);
console.log("Interval cleared");
}
}, 1000);
Hello 1 Hello 2 Hello 3 Interval cleared
How to Clear setInterval
To stop a setInterval(), use clearInterval() with the interval ID:
// Store the interval ID
let intervalId = setInterval(function() {
console.log("This runs every second");
}, 1000);
// Clear it after 3 seconds
setTimeout(function() {
clearInterval(intervalId);
console.log("Interval stopped");
}, 3000);
This runs every second This runs every second This runs every second Interval stopped
Common Use Cases
Here's a practical example of a countdown timer:
let timeLeft = 5;
let countdown = setInterval(function() {
console.log("Time left: " + timeLeft + " seconds");
timeLeft--;
if (timeLeft
Time left: 5 seconds
Time left: 4 seconds
Time left: 3 seconds
Time left: 2 seconds
Time left: 1 seconds
Time left: 0 seconds
Time's up!
Key Points
- Always store the interval ID returned by
setInterval() - Use
clearInterval(intervalId)to stop the execution - Intervals continue running until explicitly cleared
- Clear intervals when they're no longer needed to prevent memory leaks
Conclusion
Use setInterval() for repeated execution and always clear it with clearInterval() when done. Remember to store the interval ID for proper cleanup.
Advertisements
