Javascript重复一次函数x次

时间:2016-02-22 15:01:21

标签: javascript

我正在尝试开发一个函数,它重复一次函数x次,只需一次,不是基于settimerintervalsettimeout或基于时间的任何事情。我不想直接使用while / for循环 ,我想使用这个重复功能。

我尝试过这样的事情:

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

eval不适用于某个功能。

5 个答案:

答案 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)

您还可以使用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中进一步了解它