2

Possible Duplicate:
Javascript closure inside loops - simple practical example

Let's imagine you create some ajax requests in a for-loop like this:

$(function(){
    for(var i=0;i<10;i++){
      $.ajax({
        url : '/',
        success : function(){
          console.log('callback '+i+' fired!');
        }
      });
    }
});

Of course, the callback will log 'callback 10 fired' every time because the callbacks are executed asynchronous. The question is: how can you know which callback fired?

jsfiddle

Community
  • 1
  • 1
Jen-Ya
  • 328
  • 4
  • 14

3 Answers3

5

Anonymous self-invoked function will solve this closure issue:

$(function(){
    for(var i=0;i<10;i++){
      (function(i) {
          $.ajax({
            url : '/',
            success : function(){
              console.log('callback '+i+' fired!');
            }
          });
      })(i);
    }
});
zerkms
  • 249,484
  • 69
  • 436
  • 539
5

create a scope with an immediately invoked function expression:

$(function(){
    for(var i=0;i<10;i++){
      (function(i){
        $.ajax({
          url : '/',
          success : function(){
            console.log('callback '+i+' fired!');
          }
        });
      })(i);
    }
});
2

By passing the current value of i as part of a closure:

$(function(){
    for(var i=0;i<10;i++){
      $.ajax({
        url : '/',
        success : (function(i){
          return function(){console.log('callback '+i+' fired!');}
        })(i)
      });
    }
});

Here is a demo: http://jsfiddle.net/rRwgW/4/

Note: you don't actually need to wrap the entire ajax call in an IIFE, just the callback that needs to refer to the value of i.

Asad Saeeduddin
  • 46,193
  • 6
  • 90
  • 139
  • Thank you very much for your answer! It works very well, but zerkms was just a bit faster, so I had to accept his answer. – Jen-Ya Nov 25 '12 at 21:37
  • 1
    @Jen-YaKovalev That's cool. For future reference, you don't need to explain your acceptance choices, we all understand. :) (My question was directed at the person who downvoted this, not you) – Asad Saeeduddin Nov 25 '12 at 21:38