I want to run a function certain amount of times using recursion, for example: repeat(console.log('Hello'), 3)
should print Hello 3 times. I tried to implement such function but it prints only one word Hello
.
function repeat(w, x){ let fun = function(arg){ return arg } if (x==1){ return fun(w) } else{ return fun(w)+repeat(fun(w), x-1) } } repeat(console.log('Hello'), 3)
Advertisement
Answer
A few mistakes in your code:
- You’re not passing the function as an argument.
- You don’t need to use
+
to make two functions run after each other. From your original snippet I infer that you’re only concerned about the side effects, not the values. So you can just call the functions individually.
It could look something like this:
function repeat(fun, x) { if(x < 1) return; // we ran out of attempts, terminate fun(); // side-effect (print to console) repeat(fun, x - 1); // decrement the counter and attempt to continue } repeat(function() { console.log("hello")}, 3);