0

I want to call multiple functions in a JavaScript 'for' loop, but they are only being called the first time and the loops terminates.

I have tried making the functions unique, by passing a value to them, using some generic function caller such as:

for(i=0; i<50; i++){
    alert('test');
    generator_function(i);
}


function generator_function(variable){
   function1(variable);
   function2(variable);
   function3(variable);
   function4(variable);
   var sum = local_array.reduce(function(a, b) { return a + b });
   var avg = sum / local_array.length;
}

Which seems to work, but the local arrays still hold the elements from the first loop.

Is there a better way of calling a collection of functions inside a loop? I have global arrays which are being altered in these loops and am wondering if they need to be local, i.e. inside the functions somehow?

7
  • 6
    one possible problem is for(i=0; i<50; i++){ here i is a global variable if inside any one of the function(where i is again in global scope) is value is changed to > 50 then the loop will get terminated. Try for( var i=0; i<50; i++){ instead Commented Aug 22, 2013 at 10:18
  • 1
    To be sure: You can see only one alert? If so, there might be an error occured when executing one of the functions in generator_function. Have you checked the console, there should be an error message. Commented Aug 22, 2013 at 10:21
  • The functions work fine on their own. I think @Arun may be right in talking about the local variable in the loops. I had a lot of those and wondered why you needed the 'var'. I will run a few tests but feel free to put that as an answer. Commented Aug 22, 2013 at 10:25
  • @Jon posting as an answer Commented Aug 22, 2013 at 10:26
  • @Jon Well, now you know, why to use var : ). Commented Aug 22, 2013 at 10:27

1 Answer 1

2

one possible problem is for(i=0; i<50; i++){ here i is a global variable if inside any one of the function(where i is again in global scope) is value is changed to > 50 then the loop will get terminated they both references the same instance in the global scope. Try for( var i=0; i<50; i++){ instead.

When you use var in a variable declaration, that variable will be created in the local scope(the function in which it is declared)

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

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.