Javascript重复一个函数x次

Javascript repeat a function x amount of times

本文关键字:一个 函数 Javascript      更新时间:2023-09-26

我正在尝试开发一个函数,该函数重复x次,仅一次,而不是基于settimerintervalsettimeout或任何基于时间的函数。 我不想直接使用 while/for 循环,我想使用这个重复函数。

我试过这样的事情:

function repeat(func, times) {
  for (x = 0; x < times; x++) {
    eval(func)
  }
}

但是eval不适用于函数。

const func = () => console.log("hi");
const times = 3;
Array.from({length: times}, () => func());

我定义了一个函数。设置重复功能的次数。我制作一个大小为次数大小的数组来重复函数。我在数组的每个元素上运行"定义的函数"。

只需调用func和递减计数器,然后再次调用函数repeat

function repeat(func, times) {
    func();
    times && --times && repeat(func, times);
}
repeat(function () { document.write('Hi<br>'); }, 5);

如果 Lodash 是一个选项,那么 _.times

您还可以

定义一个可重用的函数,利用setIntervalclearInterval

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

使用递归:

function repeat(fn, times) {
  var loop = function (times) {
    if (times) {
      fn(times);
      loop(--times);
    }
  }
  loop(times);
}
repeat(function (times) {
  console.log(times);
}, 5);

你可能无法 eval() 函数,但你可以调用它。这是修复:

function repeat(func, times) {
  for (x = 0; x < times; x++) {
    func()
  }
}