Itslearning Itslearning - 1 month ago 11
Javascript Question

detecting internet speed in Javascript?

I have found really good example her stackoverflow how to detect internet speed with JavaScript. But when I run the code it shows 1.14 Mbps but in real speed test service i do get over 80 Mbps. Would any one tell me why is that and how can I improve this?

var imageAddr = "http://www.w3schools.com/css/trolltunga.jpg";
var downloadSize = 45941; //bytes

function ShowProgressMessage(msg) {
if (console) {
if (typeof msg == "string") {
console.log(msg);
} else {
for (var i = 0; i < msg.length; i++) {
console.log(msg[i]);
}
}
}

var oProgress = document.getElementById("progress");
if (oProgress) {
var actualHTML = (typeof msg == "string") ? msg : msg.join("<br />");
oProgress.innerHTML = actualHTML;
}
}

function InitiateSpeedDetection() {
ShowProgressMessage("Testing your internet connection quality...");
window.setTimeout(MeasureConnectionSpeed, 1);
};

if (window.addEventListener) {
window.addEventListener('load', InitiateSpeedDetection, false);
} else if (window.attachEvent) {
window.attachEvent('onload', InitiateSpeedDetection);
}

function MeasureConnectionSpeed() {
var startTime, endTime;
var download = new Image();
download.onload = function () {
endTime = (new Date()).getTime();
showResults();
}

download.onerror = function (err, msg) {
ShowProgressMessage("Invalid image, or error downloading");
}

startTime = (new Date()).getTime();
var cacheBuster = "?nnn=" + startTime;
download.src = imageAddr + cacheBuster;

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);
ShowProgressMessage([
"Your connection speed is:",
speedBps + " bps",
speedKbps + " kbps",
speedMbps + " Mbps"
]);
}
}

Answer

I think this is a problem with the behavior how packages are transfered in the web.

I cannot explain it 100% but the transmission start with a lower speed than possible and increases during transfer when possible. So you will never get the maximum speed when you are doing measuring that way. You can get near to maximum speed when you are downloading a bigger file (try 5mb) and you will get are more precise result.