JSFiddle - React, Tailwind, and code Playground

by BurpmanJunior

HTML

<input id="pingUrl" type="text" value="http://google.com"></input>
<button id="pinger">Ping</button>

JavaScript

/**
 * Ping functions
 * Example: ping.run('http://yourtest.com', function(response){ console.log(response.url + ' : ' + response.delta); });
 * @type {Object}
 */
var ping = {

    /**
     * Request timeout in ms
     * @type {Number}
     */
    timeout: 3000,

    /**
     * Runs primary ping function and provides a callback
     * @param  {String}   url      URL to ping
     * @param  {Function} callback Callback function ({url, delta})
     */
    run: function (url, callback) {
        ping.ping(url).then(function (delta) {
            callback({
                url, delta
            });
        }).
        catch (function (error) {
            console.error(error);
        });
    },

    /**
     * Creates image to run load test
     * @param  {String} url URL to load
     * @return {Function}   Promise resolve/reject
     */
    requestImage: function (url) {
        return new Promise(function (resolve, reject) {
            var img = new Image();
            img.onload = function () {
                resolve(img);
            };
            img.onerror = function () {
                reject(url);
            };
            img.src = url + '?random-no-cache=' + Math.floor((1 + Math.random()) * 0x10000).toString(16);
        });
    },

    /**
     * Primary ping function
     * @param  {String} url URL to ping
     * @return {Function}   Promise resolve/reject
     */
    ping: function (url) {
        return new Promise(function (resolve, reject) {
            var start = (new Date()).getTime();
            var response = function () {
                var delta = ((new Date()).getTime() - start);
                delta /= 4; // Fudge factor to correct the ping for HTTP bulk
                resolve(delta);
            };
            ping.requestImage(url).then(response).
            catch (response);
            setTimeout(function () {
                reject(Error('Timeout'));
            }, ping.timeout);
        });
    }

}

/**
 * Ping functions
...