Calculating speed using JavaScript returns NaN

☆樱花仙子☆ 提交于 2019-12-02 16:40:26

问题


I am following the sample shown here How to detect internet speed in Javascript? where an image with known file size is downloaded from the web and the speed is determined. For some reason I am not getting a result. My implementation is slightly different in that I am calling the JavaScript using InvokeScript and getting the value via ScriptNotify. My result value, however, is NaN. What can I do to fix this?

JavaScript

var imageAddr = "http://www.tranquilmusic.ca/images/cats/Cat2.JPG";
    var startTime, endTime;
    var downloadSize = 5616998;
    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; //Math.round()
        var bitsLoaded = downloadSize * 8;
        var speedBps = (bitsLoaded / duration).toFixed(2);
        var speedKbps = (speedBps / 1024).toFixed(2);
        var speedMbps = (speedKbps / 1024).toFixed(2);

        window.external.notify("COT" + speedMbps);
    }

C#

private void RunTestButton_Click(object sender, RoutedEventArgs e)
    {
        object connectionType = Browser.InvokeScript("showResults");
    }

private void Browser_ScriptNotify(object sender, NotifyEventArgs e)
    {
        string value = null;
        value = e.Value.ToString();

        TempResultTextBlock.Text = value;
    }

来源:https://stackoverflow.com/questions/22777362/calculating-speed-using-javascript-returns-nan

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!