internet speed checker javascript

Solutions on MaxInterview for internet speed checker javascript by the best coders in the world

showing results for - "internet speed checker javascript"
Jacopo
10 May 2020
1//JUST AN EXAMPLE, PLEASE USE YOUR OWN PICTURE!
2var imageAddr = "http://www.kenrockwell.com/contax/images/g2/examples/31120037-5mb.jpg"; 
3var downloadSize = 4995374; //bytes
4
5function ShowProgressMessage(msg) {
6    if (console) {
7        if (typeof msg == "string") {
8            console.log(msg);
9        } else {
10            for (var i = 0; i < msg.length; i++) {
11                console.log(msg[i]);
12            }
13        }
14    }
15    
16    var oProgress = document.getElementById("progress");
17    if (oProgress) {
18        var actualHTML = (typeof msg == "string") ? msg : msg.join("<br />");
19        oProgress.innerHTML = actualHTML;
20    }
21}
22
23function InitiateSpeedDetection() {
24    ShowProgressMessage("Loading the image, please wait...");
25    window.setTimeout(MeasureConnectionSpeed, 1);
26};    
27
28if (window.addEventListener) {
29    window.addEventListener('load', InitiateSpeedDetection, false);
30} else if (window.attachEvent) {
31    window.attachEvent('onload', InitiateSpeedDetection);
32}
33
34function MeasureConnectionSpeed() {
35    var startTime, endTime;
36    var download = new Image();
37    download.onload = function () {
38        endTime = (new Date()).getTime();
39        showResults();
40    }
41    
42    download.onerror = function (err, msg) {
43        ShowProgressMessage("Invalid image, or error downloading");
44    }
45    
46    startTime = (new Date()).getTime();
47    var cacheBuster = "?nnn=" + startTime;
48    download.src = imageAddr + cacheBuster;
49    
50    function showResults() {
51        var duration = (endTime - startTime) / 1000;
52        var bitsLoaded = downloadSize * 8;
53        var speedBps = (bitsLoaded / duration).toFixed(2);
54        var speedKbps = (speedBps / 1024).toFixed(2);
55        var speedMbps = (speedKbps / 1024).toFixed(2);
56        ShowProgressMessage([
57            "Your connection speed is:", 
58            speedBps + " bps", 
59            speedKbps + " kbps", 
60            speedMbps + " Mbps"
61        ]);
62    }
63}