Ben Lin
2025-03-07 ce374a9f4920a2d0e5ebe81a9872436088db6d55
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import { isBrowser } from './isBrowser';
import { isDocumentVisible } from './isDocumentVisible';
 
type Listener = () => void;
 
const listeners: Listener[] = [];
 
if (isBrowser) {
  const revalidate = () => {
    if (!isDocumentVisible()) return;
    for (let i = 0; i < listeners.length; i++) {
      const listener = listeners[i];
      listener();
    }
  };
  window.addEventListener('visibilitychange', revalidate, false);
}
 
export default function subscribe(listener: Listener) {
  listeners.push(listener);
  return function unsubscribe() {
    const index = listeners.indexOf(listener);
    listeners.splice(index, 1);
  };
}