Why does the enhancer "lose" the loop? [duplicate]

7

Making a simple loop FOR , I encountered a strange behavior that I could not understand.

The count is "lost" in the AJAX request, keeping the incrementer value with the last one. The URL request always returns 200 and still does not influence anything for proper execution.

Is there anything related to variable scope?

for (i = 0; i < 60; i++) {

  console.log("For:" + i);

  var urlMapas = "http://servicomapas.ibge.gov.br/api/mapas/" + i + '/1';

  $.ajax({
    url: urlMapas,
    dataType: "json",
    success: function(data) {
      console.log("AJAX:" + i);

    }
  });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
asked by anonymous 27.05.2016 / 00:01

1 answer

7

He does not get lost, he does exactly what he was told to do. Tie is one thing and the last function for jQuery is another completely separate. This is because the function is a closure . It captures the variable, but not its state. So only the final state is considered.

As can be seen on the console, the loop counts from 0 to 60 perfectly, and i gets this value when it closes.

The solution is to create a function and pass the loop variable as a parameter to this function. And this function is what you should call AJAX.

for (var i = 0; i < 60; i++) {
    console.log("For:" + i);
    (function(p) {
        $.ajax({
            url: "http://servicomapas.ibge.gov.br/api/mapas/" + p + '/1',
            dataType: "json",
            success: function(data) {
                console.log("AJAX:" + p);
            }
        });
    })(i);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

That's why I say that the closure should only be used in the latter case when the person knows all the consequences of it. jQuery abuses closures .

    
27.05.2016 / 00:19