Rajeev
Rajeev

Reputation: 46979

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

Upvotes: 22

Views: 65503

Answers (4)

ilumin
ilumin

Reputation: 608

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

var duration = (endTime - startTime)/1000;

Upvotes: 3

gblazex
gblazex

Reputation: 50137

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

Example with an image loading for 300 ms:

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

Leave Math.round out of the snippet.

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

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

Upvotes: 8

Thai
Thai

Reputation: 11372

Just don't round the duration.

 var duration = (endTime - startTime) / 1000;

Upvotes: 9

cdhowie
cdhowie

Reputation: 169488

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

Upvotes: 8

Related Questions