Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jdaly13/268574a5cb001f752584db88db3786fd to your computer and use it in GitHub Desktop.
Save jdaly13/268574a5cb001f752584db88db3786fd to your computer and use it in GitHub Desktop.
polling with pagelifecyle api
React.useEffect(() => {
const id = setInterval(() => {
if (document.visibilityState === 'visible') {
liveData.load("/drops");
}
}, 10000);
return () => clearInterval(id);
}, []);
const pageLifeCyleEvents = ['focus', 'blur', 'pageshow', 'pagehide', 'freeze', 'resume'];
const getDocumentState = () => {
if (document.visibilityState === 'hidden') {
return 'hidden';
}
if (document.hasFocus()) {
return 'active';
}
return 'passive';
};
React.useEffect(() => {
let id: NodeJS.Timer;
function checkPolling () {
const state = getDocumentState();
switch(state) {
case 'hidden':
case 'passive':
clearInterval(id);
break;
case 'active':
id = setInterval(() => {
liveData.load("/drops");
}, 10000);
}
}
pageLifeCyleEvents.forEach((type) => {
window.addEventListener(type, checkPolling);
});
return () => {
pageLifeCyleEvents.forEach((type) => {
window.removeEventListener(type, checkPolling);
});
}
}, []);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment