Javascript how to clear interval after specific time

setInterval("FunctionA()", 1000); 

Now, how can I clear this interval in exactly 5 seconds to achieve -

 var i = setInterval("FunctionA()", 1000); (After 5 seconds) clearInterval(i); 
+4
source share
2 answers

You can do this with the setTimeout function:

 var i = setInterval(FunctionA ,1000); setTimeout(function( ) { clearInterval( i ); }, 5000); 
+18
source

Using setTimeout for clearInterval is not an ideal solution. It will work, but it will run your setTimeout on every interval. This is normal if you are only clearing the interval, but it can be bad if you are executing other code, in addition to clearing the interval. The best solution is to use a counter. If your interval fires every 1000 ms / s, then you know if it shoots 5 times, it was 5 seconds. It is much cleaner.

 count=0; var x=setInterval(function(){ // whatever code if(count > 5) clearInterval(x); count++; }, 1000); 
+4
source

All Articles