0

Possible Duplicate:
Javascript closure inside loops - simple practical example

for (i=0; i<N; i++) {
   $.get("script"+ i +".jsp", function() {
       //I want to use i here
       //but by the time the ajax request comes back i==N, but I want the old i
   })
}

So I got this code and I was wondering if there is a better way to do it than the one from my response. This is not about jquery ajax calls, I'm aware there are ways to pass "i" through the event object, I want a general solution better than the one I came up with.

Community
  • 1
  • 1
Hoffmann
  • 14,369
  • 16
  • 76
  • 91
  • Well, this is rather trivial question, as well as the answer. By all means using closures is a silver bullet here. – VisioN Jan 11 '13 at 14:06
  • 1
    Another way would be to use `.bind` but that only works if you are not relying on `this` being set to a specific value by the calling code. You can always use a function generator and pass the value to it (instead of using a function expression). – Felix Kling Jan 11 '13 at 14:12

1 Answers1

1

Making a self-executing function to hold i works, but is very ugly:

for (i=0; i<N; i++) {
   (function(i) {
      $.get("script"+ i +".jsp", function() {
          //I want to use i here
          //but by the time the ajax request comes back i==N, but I want the old i
      })
   } (i) );
}
Hoffmann
  • 14,369
  • 16
  • 76
  • 91