Javascript 使用javascript计算速度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4583395/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 13:04:54  来源:igfitidea点击:

Calculate speed using javascript

javascript

提问by Rajeev

In the code below, I am trying to calculate the download speed of an image, but the speed comes out as infinity. What am I doing wrong?

在下面的代码中,我试图计算图像的下载速度,但速度显示为无穷大。我究竟做错了什么?

var imageAddr = "/images/image.jpg" + "?n=" + Math.random();
var startTime, endTime;
var downloadSize = 200000;
var download = new Image();
download.onload = function () {
    endTime = (new Date()).getTime();
    showResults();
}
startTime = (new Date()).getTime();
download.src = imageAddr;

function showResults() {
    var duration = Math.round((endTime - startTime) / 1000);
    var bitsLoaded = downloadSize * 8;
    var speedBps = Math.round(bitsLoaded / duration);
    var speedKbps = (speedBps / 1024).toFixed(2);
    var speedMbps = (speedKbps / 1024).toFixed(2);
    alert("Your connection speed is: \n" + 
           speedBps + " bps\n"   + 
           speedKbps + " kbps\n" + 
           speedMbps + " Mbps\n" );
}

回答by gblazex

Just think about it: endTimeand startTimeare in [ms], so their difference is also in ms.

想一想:endTimeand startTimeare in [ms],所以它们的区别也在ms。

Example with an image loading for 300 ms:

图像加载时间为300 毫秒的示例:

Math.round((endTime - startTime) / 1000);
-> Math.round(300 / 1000);
-> Math.round(0.3);
-> 0

Leave Math.roundout of the snippet.

离开Math.round片段。

And then as the others stated duration = 0will lead to

然后正如其他人所说duration = 0将导致

speedBps = bitsLoaded / duration
-> speedBps = bitsLoaded / 0
-> speedBps = Infinity

But, please note that you can't get accurate results like this. There is latency, connection time, time to first byte, etc which cannot be measuredby your example, and for an image < 1 MBthey will lead to very inaccurate results.

但是,请注意,您无法获得这样的准确结果。您的示例无法测量延迟、连接时间、到第一个字节的时间等,对于 < 1 MB的图像,它们将导致非常不准确的结果。

回答by cdhowie

durationis probably coming out 0, and a positive number divided by zero yields the special value of positive infinity in JavaScript.

duration很可能是 0,正数除以零产生 JavaScript 中正无穷大的特殊值。

回答by Thai

Just don't round the duration.

只是不要舍入持续时间。

 var duration = (endTime - startTime) / 1000;

回答by ilumin

because your duration is close to 0, then you should try

因为你的持续时间接近于 0,那么你应该尝试

var duration = (endTime - startTime)/1000;

var 持续时间 = (endTime - startTime)/1000;