3

I'm trying to figure out how to generate functions inside for loop. I have:

for (var i = fir_0_f.length - 1; i >= 0; i--){
  var next = i+1;
  var N = i;
  // Attemps
      //goal0_[i](next,N);
      //eval('goal0_'+i+'('+next+', '+N+')');
}; 

Have done also some searching. [] expects a string, eval() is a B.A.D practice. Is there any other way? How to set the timeout for each function later? So they would run sequentally?

Thanks a lot!

1
  • Can you show the code where the functions are defined? Changing that might simplify things. Commented Sep 3, 2010 at 10:34

3 Answers 3

4

In JavaScript you could use function expressions to build an array of functions:

var goals = [];

goals.push((function (param1, param2) {
   // your code for the first function
}));

goals.push((function (param1, param2) {
   // your code for the second function
}));

// ... etc

Then in your for loop, you can simply reference your functions as elements of an array:

goals[i](next, N);

UPDATE:

To call your functions with a delay between each other, you'd have to change your loop logic. Instead of using a for loop, call the first function immediately, and then after it runs, make it call the second one using a setTimeout().

Sign up to request clarification or add additional context in comments.

2 Comments

Good idea. How then run each function with timeout in for loop? First would execute immediately, others with timeout.
@c4rrt3r: Updated my answer with a comment on the timeout.
1
for (var i = fir_0_f.length - 1; i >= 0; i--){
  var next = i+1;
  var N = i;
  setTimeout('goal0_'+i+'('+next+','+N+')', 0);
}

Note: errors thrown by goal0_i won't be caught by the loop. I've noticed this behavior in Firefox. That means that the following won't work as you expected:

try{
   setTimeout(function_throwing_error, 0);
}
catch(e){
   alert("I kill you!");
}

Comments

0

For global functions, you can just do:

window['goal0_'+i](next, N);

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.