Calculate speed using javascript

前端 未结 4 1867
忘掉有多难
忘掉有多难 2020-12-05 03:08

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 = \"/         


        
4条回答
  •  感情败类
    2020-12-05 03:42

    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.

提交回复
热议问题