How to loop a function?

I’ve heard of the for and while things but I just don’t understand them. What I want to do is something like this:

var cookies = 0;
MyFunction();

function MyFunction(){
cookies ++;
yield WaitForSeconds(5);
MyFunction();
}

Whenever I try and do this, I keep getting an error message. I know about using InvokeRepeating, but I already used it in this script with the CancelInvoke, so that would mess everything up if I used it again. So how would I be able to do this?

Hello
The code construct you have has an endless recursive call and will cause a stack overflow.

To call the method over and over again, you could use the folowing code (Not tested!):

var cookies = 0;

function OnEnable()
{
    // Calls the MyFunction and calls it all 5 seconds
    InvokeRepeating("MyFunction", 0, 5);
}

function OnDisable()
{
    // Stops the repeating call
    CancelInvoke("MyFunction");
}

function MyFunction()
{
    cookies++;
}

I hope that the code isn’t incorrect because normaly I write in C#.

Greetings
Chillersanim

In that script you are never going to escape the MyFunction function. Thus Unity will hang and will appear that it is frozen. What you most likely want to do is something like:

void Update(){
int numberOfTimesToRun = 1;
for(int i = 0; i < numberOfTimesToRun; ++i)
   MyFunction();
}

function MyFunction(){
yield WaitForSeconds(5);
}

Source for the information below: JavaScript for Loop

"The for loop is often the tool you will use when you want to create a loop.

The for loop has the following syntax:

for (statement 1; statement 2; statement 3)
{
  the code block to be executed
}

Statement 1 is executed before the loop (the code block) starts.

Statement 2 defines the condition for running the loop (the code block).

Statement 3 is executed each time after the loop (the code block) has been executed."