我正在尝试开发一个函数,它重复一次函数x次,只需一次,不是基于settimerinterval
或settimeout
或基于时间的任何事情。我不想直接使用while / for循环 ,我想使用这个重复功能。
我尝试过这样的事情:
function repeat(func, times) {
for (x = 0; x < times; x++) {
eval(func)
}
}
但eval
不适用于某个功能。
答案 0 :(得分:6)
只需调用func
并递减计数器并再次调用函数repeat
。
function repeat(func, times) {
func();
times && --times && repeat(func, times);
}
repeat(function () { document.write('Hi<br>'); }, 5);
答案 1 :(得分:0)
使用递归:
function repeat(fn, times) {
var loop = function (times) {
if (times) {
fn(times);
loop(--times);
}
}
loop(times);
}
repeat(function (times) {
console.log(times);
}, 5);
答案 2 :(得分:0)
如果可以选择Lodash,则_.times
答案 3 :(得分:0)
const func = () => console.log("hi");
const times = 3;
Array.from({length: times}, () => func());
我定义一个函数。 我设置重复功能的次数。 我使数组具有重复功能的时间大小。 我在数组的每个元素上运行“定义的函数”。
答案 4 :(得分:0)
您还可以使用setInterval
和clearInterval
function runFunctionXTimes(callback, interval, repeatTimes) {
let repeated = 0;
const intervalTask = setInterval(doTask, interval)
function doTask() {
if ( repeated < repeatTimes ) {
callback()
repeated += 1
} else {
clearInterval(intervalTask)
}
}
}
function sayHi() {
console.log("Hi")
}
下一行将运行sayHi
5次,而不会浪费一个完成和另一个开始之间的时间。
runFunctionXTimes(sayHi, 0, 5)
也可以将函数参数传递给setInerval
,您可以在这里https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval中进一步了解它