Calculate speed using javascript

前端 未结 4 1751
忘掉有多难
忘掉有多难 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:40

    Just don't round the duration.

     var duration = (endTime - startTime) / 1000;
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-05 03:42

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

    0 讨论(0)
  • 2020-12-05 03:48

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

    var duration = (endTime - startTime)/1000;

    0 讨论(0)
提交回复
热议问题