JSFiddle - React, Tailwind, and code Playground

by Daniel Lamb

JavaScript

/*
var imageAddr = "http://www.google.com/images/phd/px.gif" + "?n=" + Math.random();
var startTime, endTime;
var downloadSize = 43; //in bytes
var download = new Image();
download.onload = function () {
    endTime = (new Date()).getTime();
    showResults();
}
startTime = (new Date()).getTime();
download.src = imageAddr;

function showResults() {
    var duration = (endTime - startTime) / 1000;
    var bitsLoaded = downloadSize * 8;
    var speedBps = (bitsLoaded / duration).toFixed(2);
    var speedKbps = (speedBps / 1024).toFixed(2);
    var speedMbps = (speedKbps / 1024).toFixed(2);
    alert("Your connection speed is: \n" + 
           speedBps + " bps\n"   + 
           speedKbps + " kbps\n" + 
           speedMbps + " Mbps\n" );
}*/
//*
var arrTimes = [];
var i = 0; // start
var timesToTest = 5;
var tThreshold = 150; //ms
var testImage = "http://www.google.com/images/phd/px.gif"; // small image in your server
var dummyImage = new Image();
var isConnectedFast = false;

testLatency(function(avg){
    isConnectedFast = (avg <= tThreshold);
    // output
    document.body.appendChild(
        document.createTextNode("Time: " + (avg.toFixed(2)) + "ms - isConnectedFast? " + isConnectedFast)
    );
});

// test and average time took to download image from server, called recursively timesToTest times
function testLatency(cb) {
    var tStart = new Date().getTime();
    if (i<timesToTest-1) {
        dummyImage.src = testImage + '?t=' + tStart;
        dummyImage.onload = function() {
            var tEnd = new Date().getTime();
            var tTimeTook = tEnd-tStart;
            arrTimes[i] = tTimeTook;
            testLatency(cb);
            i++;
        };
    } else {
        // calculate average of array items then callback
        var sum = arrTimes.reduce(function(a, b) { return a + b; });
        var avg = sum / arrTimes.length;
        cb(avg);
    }
}
//*/