Internet speed increases on using setInterval React

Viewed 136

I am trying to calculate internet download speed. If I call the function only once, in useEffect(), the download speed is correctly displayed. But if I want to check it multiple times, after a specific interval, resulted speed has a strange behavior - eg increases from 43 to 200.

These are the functions from utils, used to calculate and display internet speed:

export function checkInternetSpeed() {
  const DOWNLOAD_SIZE = 609 * 101 * 32;
  var download = new Image();
  var startTime = new Date().getTime();
      var cacheBuster = "?nnn=" + startTime;
      download.src = DOWNLOAD_IMAGE_ADDRESS + cacheBuster;
      download.id = cacheBuster;
      download.onload = () => {
      var endTime = new Date().getTime();
      showResults(endTime, startTime, DOWNLOAD_SIZE);
   };
}

export function showResults(endTime: number, startTime: number, downloadSize: number) {
  var duration = (endTime - startTime) / 1000; // ms -> s
  var bitsLoaded = downloadSize * 8;
  var speedBps: number = bitsLoaded / duration;
  var speedKbps: number = speedBps / 1024;
  var speedMbps: number = speedKbps / 1024;
  console.log('youuu ' + speedMbps);
  if (speedMbps < 15) {
    message.warn('Poor network connection.');
  }

The corect result is shown if I call the function only once:

 useEffect(() => {
    checkInternetSpeed();
  }, []);

But if I try to calculate it on a specific interval, the speed is increasing for no reason. enter image description here

 useEffect(() => {
  const interval = setInterval(() => {
    checkInternetSpeed();
  }, 60000);
  return () => clearInterval(interval);
}, []);

Maybe download image should be destroyed or onLoad execution should be stopped after every execution? PLEASE HELP ME

0 Answers
Related