What i am trying to achieve:
Testing the speed of download of a binary file using javascript.
I went through this link: How to detect internet speed in Javascript? and got the idea on how this can be done. Now this involves downloading the image only once and doing the calculation to get the result. Next to get better results i tried to send the repetitive ajax calls to my apache server till 10 seconds. Get the result, calculate the speed and save the result in an array. At last calculate the average of all the speeds which gives the result.
Problem is if i am using the async: false the browser becomes unresponsive while using async:true is causing the loop to go infinitely and also i am not able to figure out how calls should be made. This is the code i have written:
var startTime = 0;
var endTime = 0;
var file = '';
var allDownloadSpeeds=[];
var timeElapsed;
var t = new Date();
var x=t.getTime();
console.log(t.getHours() + " " + t.getMinutes() + " " + t.getSeconds());
t.setSeconds(t.getSeconds() + 10);
var y=t.getTime();
console.log(t.getHours() + " " + t.getMinutes() + " " + t.getSeconds());
var timeOfTest=y-x;
function DownloadTest() {
timeElapsed = 0;
var speed;
while(true){
startTime = new Date().getTime();
if(timeElapsed<timeOfTest){
$.ajax({
type: "GET",
url: "file.bin?id=" + startTime,
dataType: 'application/octet-stream',
async:false,
success: function(msg) {
binfile = msg;
endTime = new Date().getTime();
timeElapsed+=(end - startTime);
diff = (end - startTime) / 1000;
bytes = msg.length;
speed = (bytes / diff) / 1024 / 1024 * 8;
allDownloadSpeeds.push(speed);
},
});
}
else{
var averageSpeed=0;
for(var i=0;i<allDownloadSpeeds.length;i++){
averageSpeed+=allDownloadSpeeds[i];
}
console.log("Speed " + averageSpeed/averageSpeed.length);
break;
}
}
}
$(document).ready(function(){
TestDownload;
});
I don't know how to handle asynchronous ajax calls. Thanks in advance for help.