I want to update the data on my page depending on whether it is active in the browser or not. This works simply with an if query against document.hasFocus()
.
But what I now also want is that when the focus goes back to the page an update happens immediately or at least within 5sec and then again normally after 30sec.
My thought now was to change the interval time within the interval. However, I have not been able to do this.
useEffect(() => {
const statusRefreshInterval = setInterval(() => {
if (document.hasFocus()) {
console.log("hasFocus:", new Date().toLocaleTimeString());
setInterval(statusRefreshInterval, 30000);
} else {
console.log("hasNoFocus:", new Date().toLocaleTimeString());
setInterval(statusRefreshInterval, 5000);
}
}, 30000);
return () => clearInterval(statusRefreshInterval);
}, []);
EDIT: In this way, I have fulfilled all my requirements:
var lastUpdate = useRef(); // needed to use variables inside useEffect
const allowedUpdatesAfterSec = 300;
useEffect(() => {
// initial update
lastUpdate.current = Date.now() / 1000;
// update when website gets focus again
window.addEventListener("focus", function () {
if (Date.now() / 1000 - lastUpdate.current > allowedUpdatesAfterSec) {
console.log("EventListenerUpdate:", new Date().toLocaleTimeString());
lastUpdate.current = Date.now() / 1000;
}
});
// update every allowedUpdatesAfterSec when website is active
const updateRefreshInterval = setInterval(() => {
if (Date.now() / 1000 - lastUpdate.current > allowedUpdatesAfterSec) {
if (document.hasFocus()) {
console.log("IntervalUpdate:", new Date().toLocaleTimeString());
lastUpdate.current = Date.now() / 1000;
}
}
}, 60000);
return () => clearInterval(updateRefreshInterval);
}, []);
I will consider switching to setTimeout instead of setInterval.