3


I have a jQuery ajax Get call inside a for javascript cycle.
Here the code:

    var number_of_ping_for_average = 4;
var ping_start_time;
    for(i = 0; i++; i < number_of_ping_for_average){

                $.ajax({
                    type: 'GET',
                    url: "http://www.exmple.com/pkt.ext",
                    timeout: 1000,
                    cache: false,
                    beforeSend: function(){
                        ping_start_time[i][new Date().getTime()];
                    },
                    success: function (data) {
                        var ping_arrive_time = new Date().getTime();
                        var ping_val = ping_arrive_time - ping_start_time[i];
                    },
                    error: function(data){
                        //timeout or 500 error
                        //@TODO fare funzionare tutto
                    }
                });
            }

As you see... i need to call variable "i" inside anonymous function... but don't work
Remember that ping_start_time must contain 3 different simultaneous value!

r1si
  • 1,136
  • 2
  • 19
  • 34

2 Answers2

3

Create a separate function for Ajax call and it should work, creating a separate function ensures the value of i will not change inn that scope.

  var number_of_ping_for_average = 4;
    var ping_start_time=[];

    function callsAjax(i){
        $.ajax({
        type: 'GET',
        url: "http://www.exmple.com/pkt.ext",
        timeout: 1000,
        cache: false,
        beforeSend: function(){
          ping_start_time[i][new Date().getTime()];
         },
        success: function (data) {
          var ping_arrive_time = new Date().getTime();
          var ping_val = ping_arrive_time - ping_start_time[i];
         },
         error: function(data){
           //timeout or 500 error
          //@TODO fare funzionare tutto
         }
      });
    }

    for(i = 0;i < number_of_ping_for_average;i++){
        callsAjax(i)                    
    }
Farhan
  • 752
  • 4
  • 10
2

best way to do this is use wrapper
for example

(function (){
 console.log("test n." + i);
})(i)

thanks a lot!

r1si
  • 1,136
  • 2
  • 19
  • 34