setInterval与循环时间

setInterval with loop time

本文关键字:时间 循环 setInterval      更新时间:2023-09-26
setInterval(function(){}, 200)

这段代码每200毫秒运行一次函数,如果我只希望函数运行10次,我该怎么做呢?

谢谢你的帮助

使用一个计数器,每次回调被执行时递增,当它达到你想要的执行次数时,使用clearInterval()终止计时器:

var counter = 0;
var i = setInterval(function(){
    // do your thing
    counter++;
    if(counter === 10) {
        clearInterval(i);
    }
}, 200);
(function(){
var i = 10;
    (function k(){
        // your code here            
        if( --i ) {
        setTimeout( k, 200 );
        }
    })()
})()

如果你想让它运行10次,它应该运行的时间是每200毫秒,那么200X10 = 2000

var interval = setInterval(yourfunction, 200);
setTimeout(function() {
    clearInterval(interval)
}, 2000);

但是它只运行了9次所以我们必须增加200毫秒

var interval = setInterval(yourfunction, 200);
setTimeout(function() {
    clearInterval(interval)
}, 2200);

或者你可以在setInterval

之前运行
yourfunction();
var interval = setInterval(yourfunction, 200);
setTimeout(function() {
    clearInterval(interval)
}, 2000);

直接使用for循环,这样更简单:

试试这段代码。

for (counter=0; counter<0; counter++) {}

可重用的方法与选项 number of loop delay time 和利用 callback 函数

const loopInterval = ( callBack, numberOfLoop, delay ) => {  
  let counter = 0;
  let i = setInterval( ()=> {
      callBack([counter, numberOfLoop]);
      counter++;
      if(counter === numberOfLoop ) clearInterval(i);
  }, delay);
}
const runThisFunctionAsCallBack = ( x ) => console.log(`Do something here...  Loop # ${x}` )
loopInterval( runThisFunctionAsCallBack, 4, 500 )

我的方法类似于JavaScripter199的方法(使用for循环),但包含了setInterval函数。见下文:

 for (let runner = 0; runner < 10; runner++) {
      setInterval(() => {
            //Some code logic of yours.
        }
      }, 200 //run every 200 milliseconds);
    }