setInterval("FunctionA()", 1000);
Now how do I clear this interval after exactly 5 seconds so that I can achieve -
var i = setInterval("FunctionA()", 1000);
(After 5 seconds)
clearInterval(i);
setInterval("FunctionA()", 1000);
Now how do I clear this interval after exactly 5 seconds so that I can achieve -
var i = setInterval("FunctionA()", 1000);
(After 5 seconds)
clearInterval(i);
You can do this using setTimeout
function:
var i = setInterval(FunctionA ,1000);
setTimeout(function( ) { clearInterval( i ); }, 5000);
Using setTimeout to clearInterval is not an ideal solution. It will work, but it will fire your setTimeout on each interval. This is ok if you're only clearing the interval, but might be bad if you're executing other code besides clearing the interval. A better solution is to use a counter. If your interval fires every 1000ms/1sec, then you know if it fires 5 times it's been 5 seconds. That's much cleaner.
count=0;
var x=setInterval(function(){
// whatever code
if(count >= 4) clearInterval(x);
count++;
}, 1000);
function intervalGap(){
let no = 1;
setInterval(function(){
if(no < 11){
console.log(no);
no++;
}else{
clearInterval(this);
}}, 500); // for every half second
}
intervalGap();
© 2022 - 2024 — McMap. All rights reserved.
setInterval("FunctionA()", 1000)
is very much equivalent tosetInterval(FunctionA, 1000)
, but the latter does not involve aneval
and is thus much more efficient. – Grecoroman