Skip to content

The platform for continuously improving AI agents.

620 B
Raw Blame
/** Runs `start` while the tab is visible and calls the stop it returns when the tab hides.
 *  A hidden tab must release its HTTP/1 connection so ordinary API reads can proceed. */
export function whilePageVisible(start: () => () => void) {
  let stop: (() => void) | undefined;
  const update = () => {
    if (document.visibilityState === "hidden") {
      stop?.();
      stop = undefined;
    } else if (!stop) {
      stop = start();
    }
  };
  document.addEventListener("visibilitychange", update);
  update();
  return () => {
    document.removeEventListener("visibilitychange", update);
    stop?.();
  };
}