Stop setInterval call in JavaScript
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()
.
If you set the return value of setInterval
to a variable, you can use clearInterval
to stop it.
var myTimer = setInterval(...);
clearInterval(myTimer);
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.
The answers above have already explained how setInterval returns a handle, and how this handle is used to cancel the Interval timer.
Some architectural considerations:
Please do not use "scope-less" variables. The safest way is to use the attribute of a DOM object. The easiest place would be "document". If the refresher is started by a start/stop button, 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.