简体   繁体   中英

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

You can do this using setTimeout function:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM