cnu
cnu

Reputation: 37245

Stop setInterval call in JavaScript

I am using setInterval(fname, 10000); to call a function every 10 seconds in JavaScript. Is it possible to stop calling it on some event?

I want the user to be able to stop the repeated refresh of data.

Upvotes: 1797

Views: 1490664

Answers (9)

Gero
Gero

Reputation: 13563

Use this if you have your counter in a button onclick.

<button onClick="inter = setInterval(myCounter, 1000)">start to count</button>

<p id="demo">here is the counter</p>

<button onClick="clearInterval(inter)">stop </button>

Upvotes: 0

Mohamed Raafat
Mohamed Raafat

Reputation: 397

const interval = setInterval(function() {
     const checkParticlesjs = document.querySelector('.success_class')  // get success_class from page
     if (checkParticlesjs) {  // check if success_class exist
         fbq('track', 'CompleteRegistration');  // Call Facebook Event
         clearInterval(interval);  // Stop Interval 
        }
 }, 2000); // repeat every 2 second

Upvotes: 7

underflow
underflow

Reputation: 2201

The Trick

setInterval returns a number:

enter image description here

Solution

Take this number. Pass it to the function clearInterval and you're safe:

enter image description here

Code:

Always store the returned number of setInterval in a variable, so that you can stop the interval later on:

const intervalID = setInterval(f, 1000);

// Some code

clearInterval(intervalID);

(Think of this number as the ID of a setInterval. Even if you have called many setInterval, you can still stop anyone of them by using the proper ID.)

Upvotes: 14

danielassayag
danielassayag

Reputation: 941

In nodeJS you can you use the "this" special keyword within the setInterval function.

You can use this this keyword to clearInterval, and here is an example:

setInterval(
    function clear() {
            clearInterval(this) 
       return clear;
    }()
, 1000)

When you print the value of this special keyword within the function you output a Timeout object Timeout {...}

Upvotes: 11

John Millikin
John Millikin

Reputation: 201006

setInterval() returns an interval ID, which you can pass to clearInterval():

var refreshIntervalId = setInterval(fname, 10000);

/* later */
clearInterval(refreshIntervalId);

See the docs for setInterval() and clearInterval().

Upvotes: 2762

Onur Yıldırım
Onur Yıldırım

Reputation: 33692

Already answered... But if you need a featured, re-usable timer that also supports multiple tasks on different intervals, you can use my TaskTimer (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();

In your case, when users click for disturbing the data-refresh; you can also call timer.pause() then timer.resume() if they need to re-enable.

See more here.

Upvotes: 15

OMGrant
OMGrant

Reputation: 1007

You can set a new variable and have it incremented by ++ (count up one) every time it runs, then I use a conditional statement to end it:

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 that it helps and it is right.

Upvotes: 71

Quintin Robinson
Quintin Robinson

Reputation: 82375

If you set the return value of setInterval to a variable, you can use clearInterval to stop it.

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

Upvotes: 138

Aart den Braber
Aart den Braber

Reputation: 862

Why not use a simpler approach? Add a class!

Simply add a class that tells the interval not to do anything. For example: on hover.

var i = 0;
this.setInterval(function() {
  if(!$('#counter').hasClass('pauseInterval')) { //only run if it hasn't got this class 'pauseInterval'
    console.log('Counting...');
    $('#counter').html(i++); //just for explaining and showing
  } else {
    console.log('Stopped counting');
  }
}, 500);

/* In this example, I'm adding a class on mouseover and remove it again on mouseleave. You can of course do pretty much whatever you like */
$('#counter').hover(function() { //mouse enter
    $(this).addClass('pauseInterval');
  },function() { //mouse leave
    $(this).removeClass('pauseInterval');
  }
);

/* Other example */
$('#pauseInterval').click(function() {
  $('#counter').toggleClass('pauseInterval');
});
body {
  background-color: #eee;
  font-family: Calibri, Arial, sans-serif;
}
#counter {
  width: 50%;
  background: #ddd;
  border: 2px solid #009afd;
  border-radius: 5px;
  padding: 5px;
  text-align: center;
  transition: .3s;
  margin: 0 auto;
}
#counter.pauseInterval {
  border-color: red;  
}
<!-- you'll need jQuery for this. If you really want a vanilla version, ask -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<p id="counter">&nbsp;</p>
<button id="pauseInterval">Pause</button></p>

I've been looking for this fast and easy approach for ages, so I'm posting several versions to introduce as many people to it as possible.

Upvotes: -5

Related Questions