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 us
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.
Declare variable to assign value returned from setInterval(...) and pass the assigned variable to clearInterval();
e.g.
var timer, intervalInSec = 2;
timer = setInterval(func, intervalInSec*1000, 30 ); // third parameter is argument to called function 'func'
function func(param){
console.log(param);
}
// Anywhere you've access to timer declared above call clearInterval
$('.htmlelement').click( function(){ // any event you want
clearInterval(timer);// Stops or does the work
});
I guess the following code will help:
var refreshIntervalId = setInterval(fname, 10000);
clearInterval(refreshIntervalId);
You did the code 100% correct... So... What's the problem? Or it's a tutorial...
Use setTimeOut to stop the interval after some time.
var interVal = setInterval(function(){console.log("Running") }, 1000);
setTimeout(function (argument) {
clearInterval(interVal);
},10000);
This is how I used clearInterval() method to stop the timer after 10 seconds.
function startCountDown() {
var countdownNumberEl = document.getElementById('countdown-number');
var countdown = 10;
const interval = setInterval(() => {
countdown = --countdown <= 0 ? 10 : countdown;
countdownNumberEl.textContent = countdown;
if (countdown == 1) {
clearInterval(interval);
}
}, 1000)
}
<head>
<body>
<button id="countdown-number" onclick="startCountDown();">Show Time </button>
</body>
</head>
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().