Dasaru
Dasaru

Reputation: 2918

How do I pass a function as a parameter to run multiple times?

I don't understand function closures and anonymous functions very well. What I'm trying to do is create a function that runs the inputted function randomly based on a dice roll:

repeat(1,6,foobar());

function repeat(numDie, dieType, func){
    var total = 0;
    for (var i=0; i < numDie; i++){
        var dieRoll = Math.floor(Math.random()*dieType)+1;
        total += dieRoll;
    }
    for (var x=0; x < total; x++){
        func();
    }
}

What exactly am I doing wrong here? Do I have to store the function in a variable to use it?

Upvotes: 2

Views: 360

Answers (2)

SLaks
SLaks

Reputation: 887657

By writing foobar(), you're calling foobar and passing its return value.

Remove the parentheses to pass the function instead of calling it.

Upvotes: 8

Chandu
Chandu

Reputation: 82933

Change:

repeat(1,6,foobar());

to

repeat(1,6,foobar); 

Upvotes: 6

Related Questions