Coder Perfect

Stop calling setInterval in JavaScript.


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 */

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(...);

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) {
          /* your code goes here */
     } else {

     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>

function start(d){
    if (d.interval){
    } else {
          //refresh here

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.
    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 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(;

// Start the timer

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