0

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;
    }
geoCode
  • 89
  • 7
  • 4
    Because `onload` is called asynchronously. – acdcjunior Jun 06 '19 at 00:31
  • `onload` will not run before `estSpeedKbps` ends. See [Jake Archibald: In The Loop - JSConf.Asia 2018](https://www.youtube.com/watch?v=cCOL7MC4Pl0). – Theraot Jun 06 '19 at 00:32
  • Because the download is async. but estSpeedKbps return result is synchronized. Move alert to the end of getResult you will see the alert – fangzhzh Jun 06 '19 at 00:32
  • You should use a callback or a promise to allow a continuation once the asynchronous code has run. – Paul Rooney Jun 06 '19 at 00:33
  • Both estSpeedKbps and getResults has the same problem. The return speedKbps will return undefined because return speedKbps will be run before getResults... check some examples of javascript async and callback code. Usually you solve this problem by passing a callback to estSpeedKbps that will be called from getResults. – user1039663 Jun 06 '19 at 00:39

0 Answers0