问题描述:

I'm trying to develop a function that repeats a function x amount of times, just once, not based on settimerinterval or settimeout or anything based on time. I don't want to use a while/for loop directly, I want to use this repeat function.

I've tried something like this:

function repeat(func, times) {

for (x = 0; x < times; x++) {

eval(func)

}

}

But eval doesn't work on a function.

网友答案:

Just call func and decrement counter and call the function repeat again.

function repeat(func, times) {
    func();
    --times && repeat(func, times);
}

repeat(function () { document.write('Hi<br>'); }, 5);
网友答案:

Using recursion:

function repeat(fn, times) {
  var loop = function (times) {
    if (times) {
      fn(times);
      loop(--times);
    }
  }
  loop(times);
}

repeat(function (times) {
  console.log(times);
}, 5);
相关阅读:
Top