使用javascript计算速度 [英] Calculate speed using javascript

查看:142
本文介绍了使用javascript计算速度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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


推荐答案

试想一下: endTime startTime [ms] 中,所以他们的区别也是在ms。

Just think about it: endTime and startTime are in [ms], so their difference is also in ms.

300毫秒的图像加载示例

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

离开 Math.round 片段。

然后其他人声明持续时间= 0 将导致

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

,请注意您无法准确结果是这样的。有延迟,连接时间,到第一个字节的时间等,无法衡量通过您的示例,以及图像< 1 MB 会导致非常不准确的结果。

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 measured by your example, and for an image < 1 MB they will lead to very inaccurate results.

这篇关于使用javascript计算速度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆