小编典典

使用javascript计算速度

javascript

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

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" );
}

阅读 315

收藏
2022-05-13

共1个答案

小编典典

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

图像加载300 毫秒的示例:

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

离开Math.round片段。

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

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

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

2022-05-13