Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ping in JavaScript or jQuery?

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?

like image 296
Kivylius Avatar asked Jan 22 '12 13:01

Kivylius


People also ask

How do I use ping in JavaScript?

Output. Open the web page in your web browser. Press 'Ctrl+Shift+I' to navigate to Browser Developer Tools. Enter the URL you wish to ping in the form input and click the 'Submit' button.

How do I ping using HTTP?

In Windows, hit Windows+R. In the Run window, type “cmd” into the search box, and then hit Enter. At the prompt, type “ping” along with the URL or IP address you want to ping, and then hit Enter.


1 Answers

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;

    }
});
like image 67
Rafay Avatar answered Oct 16 '22 23:10

Rafay