ReactJS : How to detect network idle between XHR requests

1k Views Asked by At

I'm fairly new to the JS world and working with React JS. Couldn't find anything for the exact solution.

I want to implement an App level idle timer which would be activated when the user does not make any server request for a specific time period. The function should be triggered after X mins of the last XHR request irrespective of whether the user navigates between components or not.

For example - If user clicks on a button which calls an API and just plays around the screen without making another service call for X mins, the function should be triggered. At this stage, though user is not idle on the website, there's an idleness in the network activity. I want to detect this and perform some actions.

Also, would like to know the performance impact of the solution. Thanks!

2

There are 2 best solutions below

0
Siva K V On BEST ANSWER

Use PerformanceObserver to detect the fetch and then add/update timer using the setTimeout

let timer;

const observer = new PerformanceObserver((items) => {
  items
    .getEntries()
    .filter(({ initiatorType }) => initiatorType === "fetch")
    .forEach((entry) => {
      console.log("Made fetch request", entry.name);
      if (timer) {
        clearTimeout(timer);
      }
      timer = setTimeout(() => console.log("(idle) After 2 sec"), 2000);
    });
});

observer.observe({
  entryTypes: ["resource"],
});

fetch("https://swapi.dev/api/planets/1/").then((res) => res.json());

setTimeout(
  () => fetch("https://swapi.dev/api/planets/2/").then((res) => res.json()),
  1000
);

setTimeout(
  () => fetch("https://swapi.dev/api/planets/3/").then((res) => res.json()),
  3000
);

0
Robert On

The Network Information Api.

I'm not sure but you can try subtract downlink from downlinkMax.

But this Api is not well supported Can i use