How to use clearInterval method In Javascript

In this approach, we are using clearInterval the interval ID returned setInterval to directly stop the repetitive task execution at any point in your code.

Example 1: Implementation to show how to stop setInterval call in JavaScript.

JavaScript
let intervalId = setInterval(() => {
    console.log('Executing repetitive task...');
}, 1000); 

// Stop the interval after 5 seconds
setTimeout(() => {
    clearInterval(intervalId);
    console.log('Interval stopped after 5 seconds.');
}, 5000);

Output:

Example 2: Implementation to show how to stop setInterval call in JavaScript using conditional check.

JavaScript
let counter = 0;
let intervalId = setInterval(() => {
    counter++;
    console.log('Counter:', counter);
    if (counter >= 5) {
        clearInterval(intervalId);
        console.log('Interval stopped after 5 iterations.');
    }
}, 1000); 

Output:


Example 3: Implementation to show how to stop setInterval call in JavaScript using .

JavaScript
let isRunning = true;
let intervalId = setInterval(() => {
    if (isRunning) {
        console.log('Executing repetitive task...');
    } else {
        clearInterval(intervalId);
        console.log('Interval stopped using flag.');
    }
}, 1000);

// Stop the interval after 5 seconds using the flag
setTimeout(() => {
    isRunning = false;
}, 5000);

Output:


How to stop setInterval Call in JavaScript ?

In JavaScript, the setInterval() function is used to repeatedly execute a specified function at a fixed interval. However, there may be scenarios where we need to stop the execution of setInterval() calls dynamically. Stopping a setInterval() call in JavaScript is essential to prevent ongoing repetitive tasks and manage resource usage efficiently.

Similar Reads

Using clearInterval method

In this approach, we are using clearInterval the interval ID returned setInterval to directly stop the repetitive task execution at any point in your code....