Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript how to clear interval after specific time

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);
like image 372
skos Avatar asked Jul 06 '12 13:07

skos


1 Answers

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 > 5) clearInterval(x);
  count++;
}, 1000);
like image 199
ironarm Avatar answered Sep 17 '22 14:09

ironarm