Javascript how to clear interval after specific time
Asked Answered
F

3

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);
Found answered 6/7, 2012 at 13:43 Comment(2)
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.Grecoroman
@Grecoroman thanks for that, appreciate itFound
W
37

You can do this using setTimeout function:

var i = setInterval(FunctionA ,1000);
setTimeout(function( ) { clearInterval( i ); }, 5000);
Welcome answered 6/7, 2012 at 13:44 Comment(1)
unfortunately this is not exact with short time intervals for example 40ms as Interval and 5000ms as timeoutAsteriated
P
18

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);
Pavlish answered 24/10, 2014 at 14:27 Comment(3)
this does not work. x is not in the scope of the functionAsteriated
@Asteriated yes it is.Hypethral
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 @PavlishEnrol
I
2
function intervalGap(){
    let no = 1;
    setInterval(function(){
    if(no < 11){
        console.log(no);
        no++;
    }else{
        clearInterval(this);
    }}, 500); // for every half second
}
intervalGap();
Insufferable answered 27/8, 2018 at 18:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.