Javascript - 告诉 setInterval 只触发 x 次?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2956966/
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
Javascript - telling setInterval to only fire x amount of times?
提问by Probocop
Is it possible to limit the amount of times that setInterval will fire in javascript?
是否可以限制 setInterval 在 javascript 中触发的次数?
回答by Daniel Vassallo
You can call clearInterval()after xcalls:
您可以clearInterval()在x 次调用后调用:
var x = 0;
var intervalID = setInterval(function () {
// Your logic here
if (++x === 5) {
window.clearInterval(intervalID);
}
}, 1000);
To avoid global variables, an improvement of the above would be:
为了避免全局变量,上述改进将是:
function setIntervalX(callback, delay, repetitions) {
var x = 0;
var intervalID = window.setInterval(function () {
callback();
if (++x === repetitions) {
window.clearInterval(intervalID);
}
}, delay);
}
Then you can call the new setInvervalX()function as follows:
然后您可以setInvervalX()按如下方式调用新函数:
// This will be repeated 5 times with 1 second intervals:
setIntervalX(function () {
// Your logic here
}, 1000, 5);
回答by Jerald Macachor
You can use setTimeout and a for loop.
您可以使用 setTimeout 和 for 循环。
var numberOfTimes = 20;
delay = 1000;
for (let i = 0; i < numberOfTimes; i++) {
setTimeout( doSomething, delay * i);
}
回答by NDavis
I personally prefer to use setTimeout()spaced out to achieve the same effect
我个人更喜欢使用setTimeout()spaced out来达到同样的效果
// 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)
}
There's no clean up required with clearInterval()
无需清理 clearInterval()
You can enclose it to avoid variables leaking and it looks pretty clean :)
您可以将其封闭起来以避免变量泄漏,并且看起来很干净:)
// 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)
回答by blow
You can set a timeout that calls clearInterval.
This should work:
您可以设置调用clearInterval. 这应该有效:
function setTimedInterval(callback, delay, timeout){
var id=window.setInterval(callback, delay);
window.setTimeout(function(){
window.clearInterval(id);
}, timeout);
}
回答by Amr Elgarhy
This will clear the interval after 10 calls
这将在 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>
回答by jimm101
I made a small package that does this for NodeJS.
我为 NodeJS 做了一个小包。
https://www.npmjs.com/package/count-interval
https://www.npmjs.com/package/count-interval
It's a drop-in replacement for setInterval (including parameter passing), but it takes an additional countparameter. This example prints a message once every second, but only 3 times.
它是 setInterval 的替代品(包括参数传递),但它需要一个额外的count参数。此示例每秒打印一次消息,但仅打印 3 次。
const countInterval = require('./countInterval');
const timer = countInterval(() => {
console.log('fired!', new Date());
}, 1000, 3);
回答by Jonas Johansson
And for those of you preferring setTimeout and loving recursion here is my suggestion ;)
对于那些喜欢 setTimeout 和喜欢递归的人,这是我的建议;)
const setIntervalX = (fn, delay, times) => {
if(!times) return
setTimeout(() => {
fn()
setIntervalX(fn, delay, times-1)
}, delay)
}
Then as suggested you can call the new setInvervalX()function as follows:
然后按照建议,您可以setInvervalX()按如下方式调用新函数:
// This will be repeated every for 5 times with 1 second intervals:
setIntervalX(function () {
// Your logic here
}, 1000, 5);

