Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate speed using javascript

Tags:

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" );
}
like image 716
Rajeev Avatar asked Jan 03 '11 09:01

Rajeev


People also ask

How to check internet speed using JavaScript?

length; var time = (endTime - startTime) / 1000; var sizeInBits = downloadSize * 8; var speed = ((sizeInBits / time) / (1024 * 1024)). toFixed(2); console. log(downloadSize, time, speed); } } request. send();

How to check upload speed using JavaScript?

JQSpeedTest is a jQuery based plugin to check network speed in between the client and your webserver/application. JQSpeedTest does NOT REQUIRE SERVER-SIDE SCRIPTING. The implementation is in pure JavaScript and uses NO FLASH.

How do you calculate speed in Java?

int speed = distance/time; because you are dividing by zero. You are dividing by zero, because on the line before you set time to zero.


1 Answers

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

like image 104
cdhowie Avatar answered Oct 02 '22 11:10

cdhowie