Stop setInterval call in JavaScript
- Published
- Reading time
- 1 min read
- Length
- 197 words
On this page
Stop setInterval call in JavaScript#
If you want to stop the execution of setInterval function in JavaScript, you can use the clearInterval() method. It clears the interval which has been set by the setInterval() method.
Syntax#
var intervalID = window.setInterval(func, delay[, param1, param2, ...]);
clearInterval(intervalID);The clearInterval() method takes an intervalID parameter, which is the ID returned by the setInterval() method. When you call clearInterval() with the intervalID, it stops the interval from executing.
Example#
var intervalID = window.setInterval(myFunc, 1000);
function myFunc() {
console.log('Hello World!');
}
// Stop the interval after 5 seconds
setTimeout(function() {
clearInterval(intervalID);
}, 5000);In this example, we set an interval to execute the myFunc() function every 1 second. Then, we use the setTimeout() method to stop the interval after 5 seconds.
Another Example#
function startTimer() {
var count = 0;
var timer = setInterval(function() {
console.log(count);
count++;
if(count === 10) {
clearInterval(timer);
}
}, 1000);
}
startTimer();In this example, we create a startTimer() function that sets an interval to execute a function every 1 second. The function logs a count variable to the console and increments it by 1 on each execution. When the count reaches 10, we call clearInterval() to stop the interval.