Javascript how to clear interval after specific ti

2019-02-05 08:36发布

问题:

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);

回答1:

You can do this using setTimeout function:

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


回答2:

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);


回答3:

function intervalGap(){
    let no = 1;
    setInterval(function(){
    if(no < 11){
        console.log(no);
        no++;
    }else{
        clearInterval(this);
    }}, 500); // for every half second
}
intervalGap();