How to ping in JavaScript or jQuery?

后端 未结 2 2222
终归单人心
终归单人心 2021-02-14 02:43

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

2条回答
  •  礼貌的吻别
    2021-02-14 03:13

    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

提交回复
热议问题