Coder Perfect

Stop calling setInterval in JavaScript.

Problem

In JavaScript, I’m using setInterval(fname, 10000); to invoke a function every 10 seconds. Is it feasible to stop calling it at a certain point in time?

I want the user to be able to stop the data from being refreshed repeatedly.

Asked by cnu

Solution #1

The interval ID returned by setInterval() can be sent to clearInterval():

var refreshIntervalId = setInterval(fname, 10000);

/* later */
clearInterval(refreshIntervalId);

setInterval() and clearInterval() have documentation ().

Answered by John Millikin

Solution #2

If the return value of setInterval is a variable, clearInterval can be used to terminate it.

var myTimer = setInterval(...);
clearInterval(myTimer);

Answered by Quintin Robinson

Solution #3

You can create a new variable and have it incremented by ++ (count up one) each time it runs, and then I finish it with a conditional statement:

var intervalId = null;
var varCounter = 0;
var varName = function(){
     if(varCounter <= 10) {
          varCounter++;
          /* your code goes here */
     } else {
          clearInterval(intervalId);
     }
};

$(document).ready(function(){
     intervalId = setInterval(varName, 10000);
});

I hope it is useful and accurate.

Answered by OMGrant

Solution #4

SetInterval returns a handle, and this handle is used to cancel the Interval timer, as mentioned in the previous replies.

Some architectural considerations:

Please don’t utilize variables with no scope. The safest method is to use a DOM object’s attribute. “Document” would be the simplest option. If a start/stop button is used to start the refresher, you can use the button itself:

<a onclick="start(this);">Start</a>

<script>
function start(d){
    if (d.interval){
        clearInterval(d.interval);
        d.innerHTML='Start';
    } else {
        d.interval=setInterval(function(){
          //refresh here
        },10000);
        d.innerHTML='Stop';
    }
}
</script>

Since the function is defined inside the button click handler, you don’t have to define it again. The timer can be resumed if the button is clicked on again.

Answered by Schien

Solution #5

I’ve already responded… My TaskTimer, on the other hand, is a feature-rich, re-usable timer that also supports numerous tasks at varying intervals (for Node and browser).

// Timer with 1000ms (1 second) base interval resolution.
const timer = new TaskTimer(1000);

// Add task(s) based on tick intervals.
timer.add({
    id: 'job1',         // unique id of the task
    tickInterval: 5,    // run every 5 ticks (5 x interval = 5000 ms)
    totalRuns: 10,      // run 10 times only. (omit for unlimited times)
    callback(task) {
        // code to be executed on each run
        console.log(task.name + ' task has run ' + task.currentRuns + ' times.');
        // stop the timer anytime you like
        if (someCondition()) timer.stop();
        // or simply remove this task if you have others
        if (someCondition()) timer.remove(task.id);
    }
});

// Start the timer
timer.start();

When users click to interrupt the data-refresh in your scenario, you can also call a timer. Then there’s pause(), and then there’s the timer. If they need to re-enable, they should use resume().

See more here.

Answered by Onur Yıldırım

Post is based on https://stackoverflow.com/questions/109086/stop-setinterval-call-in-javascript