Skip to content

fix: update autorefresh if more that autorefresh in inactive tab passed #2140

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 15, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 32 additions & 9 deletions src/utils/hooks/useAutoRefreshInterval.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,26 +4,49 @@ import {AUTO_REFRESH_INTERVAL} from '../constants';

import {useSetting} from './useSetting';

const IMMEDIATE_UPDATE_INTERVAL = 1;
const DISABLED_INTERVAL = 0;

export function useAutoRefreshInterval(): [number, (value: number) => void] {
const [settingValue, setSettingValue] = useSetting(AUTO_REFRESH_INTERVAL, 0);
const [settingValue, setSettingValue] = useSetting(AUTO_REFRESH_INTERVAL, DISABLED_INTERVAL);
const [effectiveInterval, setEffectiveInterval] = React.useState(
document.visibilityState === 'visible' ? settingValue : 0,
document.visibilityState === 'visible' ? settingValue : DISABLED_INTERVAL,
);

const lastHiddenTimeRef = React.useRef<number | null>(null);

React.useEffect(() => {
// Update the effective interval when the setting changes
setEffectiveInterval(document.visibilityState === 'visible' ? settingValue : 0);

// Handle visibility change events
const handleVisibilityChange = () => {
setEffectiveInterval(document.visibilityState === 'visible' ? settingValue : 0);
const isVisible = document.visibilityState === 'visible';
if (isVisible) {
// If more than settingValue milliseconds have passed since the page was hidden,
// trigger an immediate update
const shouldTriggerImmediate =
lastHiddenTimeRef.current &&
settingValue !== DISABLED_INTERVAL &&
Date.now() - lastHiddenTimeRef.current >= settingValue;

if (shouldTriggerImmediate) {
setEffectiveInterval(IMMEDIATE_UPDATE_INTERVAL);

setTimeout(() => {
setEffectiveInterval(settingValue);
}, 0);
} else {
setEffectiveInterval(settingValue);
}

lastHiddenTimeRef.current = null;
} else {
lastHiddenTimeRef.current = Date.now();
setEffectiveInterval(DISABLED_INTERVAL);
}
};

document.addEventListener('visibilitychange', handleVisibilityChange);

return () => {
document.removeEventListener('visibilitychange', handleVisibilityChange);
};
return () => document.removeEventListener('visibilitychange', handleVisibilityChange);
}, [settingValue]);

return [effectiveInterval, setSettingValue];
Expand Down
Loading