Using pingjs

Pingjs is a JavaScript library. It cleverly use the JavaScript’s native Image object to find the responsive time. Its example use has been provided by the author. The first “ping” to your target server is always incorrect. It counts the DNS resolve time in, hence I implemented this API to an endless loop of ping, to provide an accurate result back to the user.

The page I am generating will list all my servers in a table and there is a column called Ping with a button to trigger it. The column’s ID is generated based on the server’s hostname. For example:


  

Once the button in the td is clicked, the button will be replaced with the ping time in millisecond and automatically updated every 2 seconds.

When I was writing the function runForever I encountered a jQuery problem. In the selector, I am unable to select the id, e.g. $("#ping_server1.example.com"), and I figured that out it was a escaping problem. In the console provided by the browser’s web tool, I am able to modify the ID manually but not by js script.

// host is passed down in runForever
$("#ping_" + host.replace(/\./g, "\\\\.")).text(String(delta) + "ms");

The concatenation does not work, but manual type without concatenation does work! I have to use the oldschool way, see my final code:

$(document.getElementById('ping_' + host)).text(String(delta) + "ms");

The entire runForever function is:

function runForever(host)
{
    ping("http://" + host).then(function(delta) {
        $(document.getElementById('ping_' + host)).text(String(delta) + "ms");
    }).catch(function(err) {
        $(document.getElementById('ping_' + host)).text(err);
    });
    setTimeout(function() {runForever(host);}, 2000);
};

Leave a comment

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.