@@ -4,26 +4,49 @@ import {AUTO_REFRESH_INTERVAL} from '../constants';
4
4
5
5
import { useSetting } from './useSetting' ;
6
6
7
+ const IMMEDIATE_UPDATE_INTERVAL = 1 ;
8
+ const DISABLED_INTERVAL = 0 ;
9
+
7
10
export function useAutoRefreshInterval ( ) : [ number , ( value : number ) => void ] {
8
- const [ settingValue , setSettingValue ] = useSetting ( AUTO_REFRESH_INTERVAL , 0 ) ;
11
+ const [ settingValue , setSettingValue ] = useSetting ( AUTO_REFRESH_INTERVAL , DISABLED_INTERVAL ) ;
9
12
const [ effectiveInterval , setEffectiveInterval ] = React . useState (
10
- document . visibilityState === 'visible' ? settingValue : 0 ,
13
+ document . visibilityState === 'visible' ? settingValue : DISABLED_INTERVAL ,
11
14
) ;
12
15
16
+ const lastHiddenTimeRef = React . useRef < number | null > ( null ) ;
17
+
13
18
React . useEffect ( ( ) => {
14
- // Update the effective interval when the setting changes
15
19
setEffectiveInterval ( document . visibilityState === 'visible' ? settingValue : 0 ) ;
16
20
17
- // Handle visibility change events
18
21
const handleVisibilityChange = ( ) => {
19
- setEffectiveInterval ( document . visibilityState === 'visible' ? settingValue : 0 ) ;
22
+ const isVisible = document . visibilityState === 'visible' ;
23
+ if ( isVisible ) {
24
+ // If more than settingValue milliseconds have passed since the page was hidden,
25
+ // trigger an immediate update
26
+ const shouldTriggerImmediate =
27
+ lastHiddenTimeRef . current &&
28
+ settingValue !== DISABLED_INTERVAL &&
29
+ Date . now ( ) - lastHiddenTimeRef . current >= settingValue ;
30
+
31
+ if ( shouldTriggerImmediate ) {
32
+ setEffectiveInterval ( IMMEDIATE_UPDATE_INTERVAL ) ;
33
+
34
+ setTimeout ( ( ) => {
35
+ setEffectiveInterval ( settingValue ) ;
36
+ } , 0 ) ;
37
+ } else {
38
+ setEffectiveInterval ( settingValue ) ;
39
+ }
40
+
41
+ lastHiddenTimeRef . current = null ;
42
+ } else {
43
+ lastHiddenTimeRef . current = Date . now ( ) ;
44
+ setEffectiveInterval ( DISABLED_INTERVAL ) ;
45
+ }
20
46
} ;
21
47
22
48
document . addEventListener ( 'visibilitychange' , handleVisibilityChange ) ;
23
-
24
- return ( ) => {
25
- document . removeEventListener ( 'visibilitychange' , handleVisibilityChange ) ;
26
- } ;
49
+ return ( ) => document . removeEventListener ( 'visibilitychange' , handleVisibilityChange ) ;
27
50
} , [ settingValue ] ) ;
28
51
29
52
return [ effectiveInterval , setSettingValue ] ;
0 commit comments