I am fairly green at javascript (and a first time stackoverflow user). I am trying to get a rough estimate of connection speed (using an image download). I want to return this value as the function result (not an alert - the top three code lines are just to demonstrate the issue) so I can use it to adjust media on my website. However, when I attempt to do so I get value of the variable is undefined.
In doing some research it appears that the problem may related to asynchronous execution of the code - the value is returned before the image finishes downloading. However, I have been unable to fix or work around the issue.
var speed;
speed = estSpeedKbps();
alert(speed);
function estSpeedKbps() {
var imageAddr = "https://www.weber.edu/ui/images/wsu-logo.svg" + "?n=" + Math.random();
var startTime, endTime;
var downloadSize = 9264;
var download = new Image();
var speedKbps;
download.onload = function () {
endTime = (new Date()).getTime();
getResults();
};
startTime = (new Date()).getTime();
download.src = imageAddr;
function getResults() {
var duration = (endTime - startTime) / 1000;
var bitsLoaded = downloadSize * 8;
var speedBps = Math.round(bitsLoaded / duration);
speedKbps = (speedBps / 1024).toFixed(2);
//var speedMbps = (speedKbps / 1024).toFixed(2);
}
return speedKbps;
}