Home > Web Front-end > JS Tutorial > How Can I Measure Internet Speed Using JavaScript?

How Can I Measure Internet Speed Using JavaScript?

DDD
Release: 2024-12-17 01:07:24
Original
896 people have browsed it

How Can I Measure Internet Speed Using JavaScript?

Detect Internet Speed with JavaScript

Many applications require the ability to measure the user's internet speed. While it's not always accurate, it can provide a helpful indication of the user's connectivity.

Approach

The solution involves loading an image with a known file size and calculating the speed based on the time taken to load it. This is done by:

  1. Loading the image and setting an onload handler.
  2. Measuring the start and end time of the image load using Date.getTime().
  3. Computing the time taken to load the image in seconds.
  4. Dividing the file size in bits by the time to obtain the speed in bits per second (bps).
  5. Converting the speed to kilobits per second (kbps) and megabits per second (mbps) for better readability.

Example

The following code provides an implementation of this approach:

var imageAddr = "https://example.com/image.png";
var downloadSize = 7300000; //bytes

function MeasureConnectionSpeed() {
  var startTime, endTime;
  var download = new Image();
  download.onload = function () {
    endTime = (new Date()).getTime();
    showResults();
  };
  
  download.onerror = function (err, msg) {
    ShowProgressMessage("Invalid image, or error downloading");
  }
  
  startTime = (new Date()).getTime();
  var cacheBuster = "?nnn=" + startTime;
  download.src = imageAddr + cacheBuster;
  
  function showResults() {
    var duration = (endTime - startTime) / 1000; //seconds
    var bitsLoaded = downloadSize * 8;
    var speedBps = (bitsLoaded / duration).toFixed(2);
    var speedKbps = (speedBps / 1024).toFixed(2);
    var speedMbps = (speedKbps / 1024).toFixed(2);
    ShowProgressMessage("Your connection speed is:");
    ShowProgressMessage(speedBps + " bps");
    ShowProgressMessage(speedKbps + " kbps");
    ShowProgressMessage(speedMbps + " mbps");
  }
}
Copy after login

The above is the detailed content of How Can I Measure Internet Speed Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template