Padnezz
Padnezz

Reputation: 89

Dosen't show the right numbers

I have this code to a game that have like a linux console and I'm doing the command ping.

When I want the code to display icpm_seq 0/1/2/3, it just shows icpm_seq 4.

Code:

function ping(IP){
   for (var i = 0; i <= 3; i++) {
       var start = new Date().getTime();
       $.post("data_script/ping.php?IP=" + IP,
       function(data){
          var newTime = new Date().getTime() - start;
          // 0: bad (isn't online)
          // 1: good (is online)
          // 2: bad hostname
          if(data == 0)
          {
              outputToConsole("Request timeout for icmp_seq " + i)
          }
          else
          {
              if(data == 1)
              {
                 outputToConsole("64 bytes from " + IP + ": icmp_seq=" + i + " ttl=64 time: " + newTime + "ms");
              }
              else
              {
                  outputToConsole("ping: Cannot resolve hostname " + IP + ": unknown host")
              }
          }
        });
      }
   }      

Upvotes: 0

Views: 34

Answers (1)

PA.
PA.

Reputation: 29339

welcome to asynchronous programming... by the time your callback function is called on return of the ping, the loop is over and i is 4.

what happens is

for i=0, i is <=3
calls ping
for i++, i is now 1, is <=3 
calls ping
for i++ , i is now 2, is <=3 
calls ping
for i++ , i is now 3, is <=3 
calls ping
for i++ , i is now 4, is > 3
breaks 
callback from ping 0
callback from ping 1
callback from ping 2
callback from ping 3

to overcome this, put your callback inside a closure, like this

(function(seq) { 
  $.post("ping.php?IP=" + IP,function(data){
    log("icmp_seq " +seq+" returns "+data);
  }
})(i);

Upvotes: 1

Related Questions