Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript repeat a function x amount of times

Tags:

javascript

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.

like image 256
noaoh Avatar asked Feb 22 '16 15:02

noaoh


1 Answers

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

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

repeat(function () { document.write('Hi<br>'); }, 5);
like image 79
Nina Scholz Avatar answered Oct 21 '22 11:10

Nina Scholz