Last active
January 7, 2022 15:37
-
-
Save jdaly13/268574a5cb001f752584db88db3786fd to your computer and use it in GitHub Desktop.
polling with pagelifecyle api
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
React.useEffect(() => { | |
const id = setInterval(() => { | |
if (document.visibilityState === 'visible') { | |
liveData.load("/drops"); | |
} | |
}, 10000); | |
return () => clearInterval(id); | |
}, []); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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