13
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);
2
  • 1
    setInterval("FunctionA()", 1000) is very much equivalent to setInterval(FunctionA, 1000), but the latter does not involve an eval and is thus much more efficient.
    – lanzz
    Jul 6, 2012 at 13:45
  • @lanzz thanks for that, appreciate it
    – skos
    Jul 6, 2012 at 13:47

3 Answers 3

37

You can do this using setTimeout function:

var i = setInterval(FunctionA ,1000);
setTimeout(function( ) { clearInterval( i ); }, 5000);
1
  • unfortunately this is not exact with short time intervals for example 40ms as Interval and 5000ms as timeout
    – daniel
    Sep 24, 2015 at 12:43
17

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);
3
  • this does not work. x is not in the scope of the function
    – daniel
    Sep 24, 2015 at 12:43
  • 2
    @daniel yes it is. Jan 17, 2017 at 22:42
  • 2
    This answer is what I've been looking for. All you have to do is wrap the setInterval into a variable and call the clearInterval at how many counts as you want! Thanks @ironarm
    – Huy Le
    Mar 19, 2017 at 5:51
2
function intervalGap(){
    let no = 1;
    setInterval(function(){
    if(no < 11){
        console.log(no);
        no++;
    }else{
        clearInterval(this);
    }}, 500); // for every half second
}
intervalGap();

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.