11

I want to create a game-like ping in Javascript, just like the game Counter Strike for example. I'm doing an AJAX call to the server (MySQL) and want to calculate the time that's taken, but I'm either calculating it wrong or have the wrong idea of pinging. Here is the code I have so far:

var time_stamp = new Date;

$.ajax({ type: "POST",
    url: "server.php",
    data: {....},
    success: function(output){ 

        ping = new Date - time_stamp;

    }
}); // btw, this code works fine now for ping

The problem is that sometimes I get 0ms or 3ms. Is this okay? It seems very fast to go to server.php, connect to database, select some rows, and return some data. Yes, this is on localhost, so it should be fast, but is it meant to be this fast? Should I be calculating it at FPS, or just each call to server.php?

tttony
  • 4,944
  • 4
  • 26
  • 41
Kivylius
  • 6,357
  • 11
  • 44
  • 71
  • I guess that it is okay. Try get some output from `server.php`, if it responses ok, it's ok :) if you use Chrome or Firebug, take a look on ajax request time. – David Rodrigues Jan 22 '12 at 14:00
  • 1
    Make sure the web server is sending headers on server.php to prevent caching. – Michael Berkowski Jan 22 '12 at 14:03
  • Thank you for the help. I investigated and Chrome is giving me 1ms lower then my calculations which is ok. – Kivylius Jan 22 '12 at 14:10
  • 2
    Adding a random number to the request prevents browser (especially IE) from caching like "server.php?r=" + Math.random(). I faced this caching problem within a similar situation and this trick worked out. – Zafer Apr 07 '12 at 17:23

2 Answers2

8

the lower response time is because by default the cache property is set to true, set it to false so that every time it goes to the server not the cache

var ping = new Date;

$.ajax({ type: "POST",
    url: "server.php",
    data: {....},
    cache:false,
    success: function(output){ 

        ping = new Date - ping;

    }
});
Rafay
  • 30,950
  • 5
  • 68
  • 101
2

You will not be able to calculate accurate latency on client side (not counting java, flash or websockets), you need the server to calculate it and return the value in a response. Getting anything other than 0ms for localhost should be enough evidence of this :P

The earliest time in connection state gets me 300ms for stackoverflow.com, while the real number is closer to 100ms.

var a = new XMLHttpRequest();

a.onreadystatechange = function () {

    if (a.readyState === a.HEADERS_RECEIVED) {
        a.abort();
        console.log(new Date - abc);
    }
};

var abc = new Date;

a.open("GET", "/");
a.send(null);

Waiting for the full response (a.DONE) took 949ms

Esailija
  • 138,174
  • 23
  • 272
  • 326