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.
Answer: Use the clearInterval() Method The setInterval() method returns an interval ID which uniquely identifies the interval. You can pass this interval ID to the global clearInterval() method to cancel or stop setInterval() call.
You cannot PAUSE the setInterval function, you can either STOP it (clearInterval), or let it run.
The clearInterval() method clears a timer set with the setInterval() method.
If you set the return value of setInterval
to a variable, you can use clearInterval
to stop it.
var myTimer = setInterval(...);
clearInterval(myTimer);
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()
.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With