Javascript – 告诉setInterval只发射x次的次数?

是否有可能限制setInterval将在JavaScript中触发的次数?

你可以在x调用后调用clearInterval()

 var x = 0; var intervalID = setInterval(function () { // Your logic here if (++x === 5) { window.clearInterval(intervalID); } }, 1000); 

为了避免全局variables,上面的改进是:

 function setIntervalX(callback, delay, repetitions) { var x = 0; var intervalID = window.setInterval(function () { callback(); if (++x === repetitions) { window.clearInterval(intervalID); } }, delay); } 

然后你可以调用新的setInvervalX()函数,如下所示:

 // This will be repeated every for 5 times with 1 second intervals: setIntervalX(function () { // Your logic here }, 1000, 5); 

不,你必须设置一个调用clearInterval的超时。 这应该工作:

 function setTimedInterval(callback, delay, timeout){ var id=window.setInterval(callback, delay); window.setTimeout(function(){ window.clearInterval(id); }, timeout); } 

我个人更喜欢使用setTimeout()间隔来达到相同的效果

 // Set a function to run every "interval" seconds a total of "x" times var x = 10; var interval = 1000; for (var i = 0; i < x; i++) { setTimeout(function () { // Do Something }, i * interval) } 

clearInterval()不需要清理

你可以附上它,以避免variables泄漏,它看起来很干净:)

 // Definition function setIntervalLimited(callback, interval, x) { for (var i = 0; i < x; i++) { setTimeout(callback, i * interval); } } // Usage setIntervalLimited(function() { console.log('hit'); // => hit...hit...etc (every second, stops after 10) }, 1000, 10) 

这将清除10次电话后的时间间隔

 <html> <body> <input type="text" id="clock" /> <script language=javascript> var numOfCalls = 0; var int=self.setInterval("clock()",1000); function clock() { var d=new Date(); var t=d.toLocaleTimeString(); document.getElementById("clock").value=t; numOfCalls++; if(numOfCalls == 10) window.clearInterval(int); } </script> </form> </body> </html>