是否可以限制 setInterval 在 javascript 中触发的次数?
Javascript - 告诉 setInterval 只触发 x 次?
IT技术
javascript
2021-02-12 01:11:22
6个回答
您可以clearInterval()
在x 次调用后调用:
var x = 0;
var intervalID = setInterval(function () {
// Your logic here
if (++x === 5) {
window.clearInterval(intervalID);
}
}, 1000);
为了避免全局变量,上述改进将是:
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 5 times with 1 second intervals:
setIntervalX(function () {
// Your logic here
}, 1000, 5);
我个人更喜欢使用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)
}
无需清理 clearInterval()
您可以将其封闭起来以避免变量泄漏,而且看起来很干净:)
// 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)
您可以使用 setTimeout 和 for 循环。
var numberOfTimes = 20;
delay = 1000;
for (let i = 0; i < numberOfTimes; i++) {
setTimeout( doSomething, delay * i);
}
您可以设置调用的超时时间clearInterval
。这应该有效:
function setTimedInterval(callback, delay, timeout){
var id=window.setInterval(callback, delay);
window.setTimeout(function(){
window.clearInterval(id);
}, timeout);
}
这将在 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>
其它你可能感兴趣的问题