在this article , 下面的函数被赋予用 setInterval()
执行一个操作 x 次setIntervalX(function () {
animateColor();
//or something
}, 3000, 4);
function setIntervalX(callback, delay, repetitions) {
var x = 0;
var intervalID = window.setInterval(function () {
callback();
if (++x === repetitions) {
window.clearInterval(intervalID);
}
}, delay);
}
callback() 在这里做什么?我正在尝试在指定的重复次数完成后执行一个功能。但是这个
setIntervalX(function () {
animateColor();
}, 3000, 4, function(){
completeFunction();
});
不起作用。也许这种语法是非常错误的。我的印象是,使用 jquery,您可以将这样的函数串在一起。
非常感谢任何见解。谢谢!
最佳答案
我认为您对描述有轻微的误解。 setIntervalX 执行交互 x 次,而您希望在迭代后有一个回调函数。
function setIntervalX(interationFunction, delay, repetitions, callbackFunction) {
var x = 0;
var intervalID = window.setInterval(function () {
iterationFunction();
if (++x === repetitions) {
callbackFunction();
window.clearInterval(intervalID);
}
}, delay);
}
setIntervalX(
function() {
// this executed every time the interval triggers
},
1000, // amount of milliseconds to delay before interval triggers
5, // amount of repetitions before interval is stopped and callback is executed
function() {
// this will be executed after the interval triggered 5 times
// so after round about 5 seconds after setIntervalX was started
}
);
关于javascript - 在使用 setInterval 调用 x 次后执行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10250860/