javascript Javascript如何在特定时间后清除间隔

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11363401/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 12:54:57  来源:igfitidea点击:

Javascript how to clear interval after specific time

javascriptsetinterval

提问by skos

setInterval("FunctionA()", 1000);

Now how do I clear this interval after exactly 5 seconds so that I can achieve -

现在我如何在 5 秒后清除这个间隔,以便我可以实现 -

var i = setInterval("FunctionA()", 1000);
(After 5 seconds)
clearInterval(i);

回答by antyrat

You can do this using setTimeoutfunction:

您可以使用以下setTimeout功能执行此操作:

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

回答by ironarm

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.

使用 setTimeout 来 clearInterval 不是一个理想的解决方案。它会起作用,但它会在每个时间间隔触发您的 setTimeout。如果您只是清除间隔,这是可以的,但如果您除了清除间隔之外还执行其他代码,则可能会很糟糕。更好的解决方案是使用计数器。如果您的时间间隔每 1000 毫秒/1 秒触发一次,那么您就知道它是否触发了 5 次,时间为 5 秒。那干净多了。

count=0;
var x=setInterval(function(){
  // whatever code
  if(count > 5) clearInterval(x);
  count++;
}, 1000);

回答by Shailesh Salekar

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