userNetworkMonitor

const useUserNetworkMonitor = () => {
  const info = {
    startTime: 0,
    duration: 5000,
  };
  let timer = null;
  const loop = (url, interval = 5 * 1000) => {
    timer = setTimeout(() => {
      const startTime = Date.now();
      info.startTime = startTime;
      const img = new Image();
      img.src = `${url}?timestamp=${startTime}`;
      const callback = () => {
        if (startTime !== info.startTime) return;
        const endTime = Date.now();
        info.duration = endTime - startTime;
        loop();
      };
      img.onload = callback;
      img.onerror = callback;
    }, interval);
  };
  const clear = () => clearTimeout(timer);
  return {
    loop,
    info,
    clear,
  };
};

  

posted @ 2024-03-11 21:07  671_MrSix  阅读(5)  评论(0编辑  收藏  举报