Skip to content

Instantly share code, notes, and snippets.

@user24
Created September 7, 2011 19:16
Show Gist options
  • Save user24/1201439 to your computer and use it in GitHub Desktop.
Save user24/1201439 to your computer and use it in GitHub Desktop.
Async Loop Pitfall
// the following code outputs: 999999999
var someArray = [1,2,3,4,5,6,7,8,9];
for(var i=0 ; i<someArray.length ; i++) {
performSomeAsyncOperation("foo", function hereIsACallback() {
console.log(someArray[i]);
});
}
@user24
Copy link
Author

user24 commented Nov 29, 2011

One way to avoid this:

// the following code outputs: 123456789

var someArray = [1,2,3,4,5,6,7,8,9];

for(var i=0 ; i<someArray.length ; i++) {
  (function looper(i) {
    performSomeAsyncOperation("foo", function hereIsACallback() {
      console.log(someArray[i]);
    });
  })(i);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment