Horje
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.

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.

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:

aaa

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:

aaa


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:

aaa




Reffered: https://www.geeksforgeeks.org


JavaScript

Related
JavaScript Program to Find Geometric mean in G.P. JavaScript Program to Find Geometric mean in G.P.
JavaScript Program to find nth term of Geometric Progression JavaScript Program to find nth term of Geometric Progression
How to Sort a Dictionary by Value in TypeScript ? How to Sort a Dictionary by Value in TypeScript ?
Find the Length Tuple in TypeScript ? Find the Length Tuple in TypeScript ?
How to Customize the Position of an Alert Box using JavaScript ? How to Customize the Position of an Alert Box using JavaScript ?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
19