tags:

views:

60

answers:

3

Hello,

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!

A: 

For global functions, you can just do:

window['goal0_'+i](next, N);
reko_t
+4  A: 

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().

Daniel Vassallo
Good idea. How then run each function with timeout in for loop?First would execute immediately, others with timeout.
c4rrt3r
@c4rrt3r: Updated my answer with a comment on the timeout.
Daniel Vassallo
+1  A: 

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!");
}
Lekensteyn