Sunday, December 4, 2016

How to test Internet Bandwidth by JavaScript

Today, I am going to write about how to measure the bandwidth speed by using JavaScript. It might be unreliable few times, but usually, it gives the basic idea that how much bandwidth/internet speed you have.

Our JavaScript is going to download the image from the internet to calculate the speed, let's see how it’s measured.

We mark the time when image-downloading is started and the time when that image is downloaded. Then we calculate the bandwidth speed by getting the differences between the times(downloadEndTime - downloadStartTime).

Let’s understand along with the code,


this.downloadSize : 1500000;  // Total size of image is 1.5 MB
var myImage = new Image();
this.startTime = (new Date()).getTime();
 // Everytime this method is invoked, the image is downloaded from Server not from Cache
var cacheBuster = "?nnn=" + this.startTime;
myImage.src = "https://raw.githubusercontent.com/sumanbogati/images/master/jstutorial/bandwidth-test.jpg" + cacheBuster;
In above code, we get the time when an image is starting to download by

this.startTime = (new Date()).getTime();
The remaining code is used to download the image, I'll describe the usage of cacheBuster towards the end of this article.
Following myImage.onload method will be invoked after an image is downloaded and that.endTime contains the time of this event.

var that = this;
myImage.onload = function () {
	that.endTime = (new Date()).getTime();
	var speedKbps = that.calculate();
}
We have 'start' and 'end' time of image-downloading process with this.startTime, and this.endTime, now the calculate method measures the speed based on these times,
calculate : function (){
	var duration = (this.endTime - this.startTime) / 1000;
	var bitsLoaded = this.downloadSize * 8;
	var speedBps = (bitsLoaded / duration).toFixed(2);
	var speedKbps = (speedBps / 1024).toFixed(2);
	return Math.round(speedKbps);
}
In above function, bitsLoaded demonstrates the total downloadable size of an image in bits. Now, we calculate the speed in bytes per second by (bitsLoaded / duration), finally we get the speed in Kbps through speedBps/1024.
Points are worth to notice:-

I applied the cacheBuster concept in above code, this technique forces the browser to a fresh download of an image from the Internet instead of Cache.
I used the jpeg image format for this tutorial because the server/internet is not able to compress this image type, so the image would be downloadable to its original size.

Live Demo

Bandwdith speed is :-




You can get the source code HERE.

1 comment:

  1. You should try using bestvpnrating.cоm and be safe about your privacy.

    ReplyDelete