2

Suppose I have a function roll() that randomly returns a value 1-6. Now, if I have another function called repeatFunction that takes a function as a parameter and a number n. The repeatFunction's purpose is to call whatever function it has as a parameter n times. However, if I were to pass roll() as a parameter, the repeatFunction would interpret it as whichever value 1-6 the roll() function returned, rather than a function. My code currently is as follows:

function repeatFunction(func, n){
    for(i = 0; i < n; i++){
        func;
    }
}
repeatFunction(roll(), 10);

How do I get it so repeatFunction interprets the func parameter as a function rather than a returned value so that I can call it again within the repeatFunction?

2 Answers 2

3

pass a reference to the roll function and call it inside the repeat function as a callback. Like this,

function repeatFunction(func, n){
    for(i = 0; i < n; i++){
        func();
    }
}
repeatFunction(roll, 10);
Sign up to request clarification or add additional context in comments.

Comments

1

You need to pass the function name rather than the returned execution.

You're executing the function roll, just pass roll.

repeatFunction(roll(), 10);
               ^

Look at this code snippet

The repeated function will execute the function fn recursively until i == n

function repeatFunction(fn, n, i){
    if (i === n) return;
    fn();
    
    repeatFunction(fn, 10, ++i);
}

var roll = function() {
  console.log('Called!');
};

repeatFunction(roll, 10, 0);
.as-console-wrapper {
  max-height: 100% !important
}
See? the function was called n times.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.