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 = \"/
Just don't round the duration.
var duration = (endTime - startTime) / 1000;
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.
duration
is probably coming out 0, and a positive number divided by zero yields the special value of positive infinity in JavaScript.
because your duration is close to 0, then you should try
var duration = (endTime - startTime)/1000;