How to make a setInterval() stop after some time or after a number of actions in JavaScript?

The setInterval() function repeatedly executes code at specified intervals. To stop it after some time or a number of actions, use clearInterval() with conditions.

Method 1: Stop After Time Duration

This example stops the interval after 10 seconds:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Stop setInterval After Time</title>
</head>
<body>
    <div id="output"></div>
    
    <script>
        var startTime = new Date().getTime();
        var output = document.getElementById('output');
        var count = 0;
        
        var interval = setInterval(function() {
            var currentTime = new Date().getTime();
            
            // Stop after 10 seconds (10000 milliseconds)
            if (currentTime - startTime > 10000) {
                clearInterval(interval);
                output.innerHTML += "<p>Interval stopped after 10 seconds</p>";
                return;
            }
            
            count++;
            output.innerHTML += "<p>Execution " + count + " at " + new Date().toLocaleTimeString() + "</p>";
        }, 2000);
    </script>
</body>
</html>
Execution 1 at 10:30:25 AM
Execution 2 at 10:30:27 AM
Execution 3 at 10:30:29 AM
Execution 4 at 10:30:31 AM
Execution 5 at 10:30:33 AM
Interval stopped after 10 seconds

Method 2: Stop After Number of Actions

This example stops after exactly 5 executions:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Stop setInterval After Count</title>
</head>
<body>
    <div id="counter"></div>
    
    <script>
        var counter = document.getElementById('counter');
        var executionCount = 0;
        var maxExecutions = 5;
        
        var interval = setInterval(function() {
            executionCount++;
            
            counter.innerHTML = "<p>Current count: " + executionCount + "</p>";
            
            // Stop after 5 executions
            if (executionCount >= maxExecutions) {
                clearInterval(interval);
                counter.innerHTML += "<p>Stopped after " + maxExecutions + " executions</p>";
            }
        }, 1000);
    </script>
</body>
</html>
Current count: 1
Current count: 2
Current count: 3
Current count: 4
Current count: 5
Stopped after 5 executions

Method 3: Combined Conditions

Stop when either condition is met - after 8 seconds OR after 3 executions:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Combined Stop Conditions</title>
</head>
<body>
    <div id="result"></div>
    
    <script>
        var result = document.getElementById('result');
        var startTime = new Date().getTime();
        var count = 0;
        var maxCount = 3;
        var maxTime = 8000; // 8 seconds
        
        var interval = setInterval(function() {
            count++;
            var elapsedTime = new Date().getTime() - startTime;
            
            result.innerHTML += "<p>Action " + count + " - Elapsed: " + Math.round(elapsedTime/1000) + "s</p>";
            
            // Stop if either condition is met
            if (count >= maxCount || elapsedTime > maxTime) {
                clearInterval(interval);
                var reason = count >= maxCount ? "maximum count reached" : "time limit exceeded";
                result.innerHTML += "<p><strong>Stopped: " + reason + "</strong></p>";
            }
        }, 2500);
    </script>
</body>
</html>
Action 1 - Elapsed: 3s
Action 2 - Elapsed: 5s
Action 3 - Elapsed: 8s
Stopped: maximum count reached

Key Points

  • clearInterval() stops the interval using the ID returned by setInterval()
  • Always store the interval ID in a variable for later cleanup
  • Use new Date().getTime() for time-based conditions
  • Increment counters for action-based conditions
  • Combine multiple conditions using logical operators

Comparison

Method Use Case Condition Type
Time-based Run for specific duration Time elapsed
Count-based Execute fixed number of times Action counter
Combined Stop when any condition met Multiple conditions

Conclusion

Use clearInterval() with conditions to stop setInterval(). Choose time-based, count-based, or combined approaches depending on your specific requirements.

Updated on: 2026-03-15T23:19:00+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements