1

I'm looking for something simple and straight forward, most of what I've pulled up on stack isn't quite what I need. I have an array that I want to loop through while calling a function after each iteration. What would that look like?

2
  • Do you mean you want to call an asynchronous function (like xmlhttprequst), wait for it to finish before processing the next element in the array? Commented Jun 9, 2013 at 1:14
  • yes something like that. I want the callback to process each row in the array. Commented Jun 9, 2013 at 1:46

3 Answers 3

5

I'm assuming you're having problems with this because of the way closures are handled in Javascript. Douglas Crockford talks about this, in his book, by using the example of a function that assigns a click event handler to an array of nodes. The "intuitive" way is:

var addHandlers=function(nodes){
    var i;
    for(i=0; i<nodes.length;++i){
        nodes[i].onClick= function {
            alert (i);
        };
    }
};

However, this is not correct: each onClick callback will show the same value of i = nodes.length-1. This is because the value of i is not copied, but referenced in each inner function. The better way would be to create a helper function that returns a callback, something along the lines of the following:

var addHandlers = function (nodes) {
    var helper = function (i){
        return function (e){
            alert (i);
        }
    }
    for (int i =0; i<nodes.length();i++){
        nodes [i].onClick=helper (i);
    }
}

Plus, this allows you to avoid creating a function at each iteration.

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

Comments

4
var arr = [1,2,3];
for(var i = 0; i < arr.length; i++){
  someFunction();
} 

Comments

1

If you want to process one elment of the array to be used in an asynchronous funcion and then process the next next element you can do something like this;

function asynchCallback(arrayToProcess,someVar){
  console.log("callback called with parameter:",someVar);
  processArray(arrayToProcess);
}

function processArray(arr){
  if(arr.length===0){
    console.log("done");
    return;
  }
  var someVar=tmp.splice(0,1);
  setTimeout(function(){
    asynchCallback(tmp,someVar[0]);
  },100);
}
//send a copy of the array:
processArray([1,2,3].concat());

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.