不要显示正确的数字

时间:2014-09-20 18:00:36

标签: javascript

我有一个类似Linux控制台的游戏的代码,我正在执行命令ping。

  

当我希望代码显示icpm_seq 0/1/2/3时,它只显示icpm_seq 4

代码:

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")
              }
          }
        });
      }
   }      

1 个答案:

答案 0 :(得分:1)

欢迎使用异步编程...当返回ping时调用回调函数时,循环结束,i为4。

会发生什么

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

要克服这个问题,请将回调放在闭包中,就像这样

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