2

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!

hokage
  • 58
  • 3

2 Answers2

3

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
);
Siva K V
  • 10,561
  • 2
  • 16
  • 29
1

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

Robert
  • 2,538
  • 1
  • 9
  • 17