1
- export default function useAutoRefresh ( refreshAction : ( ) => Promise < void > , timeout : number ) {
1
+ import { ref } from "vue" ;
2
+
3
+ /**
4
+ * Enables refresh functionality, either auto or manual
5
+ * @param refreshAction The action to perform (by default) when refreshing
6
+ * @param defaultTimeout The time between refreshes in ms or null if no auto-refresh is desired
7
+ */
8
+ export default function useAutoRefresh ( refreshAction : ( ) => Promise < void > , defaultTimeout : number | null , startImmediately = true ) {
2
9
let refreshInterval : number | null = null ;
10
+ const timeout = ref ( defaultTimeout ) ;
3
11
4
12
function stopTimer ( ) {
5
13
if ( refreshInterval !== null ) {
@@ -9,10 +17,12 @@ export default function useAutoRefresh(refreshAction: () => Promise<void>, timeo
9
17
}
10
18
11
19
function startTimer ( ) {
20
+ if ( timeout . value === null ) return ;
21
+
12
22
stopTimer ( ) ;
13
23
refreshInterval = window ?. setTimeout ( ( ) => {
14
24
executeAndResetTimer ( ) ;
15
- } , timeout ) ;
25
+ } , timeout . value as number ) ;
16
26
}
17
27
18
28
async function executeAndResetTimer ( overrideAction ?: ( ) => Promise < void > ) {
@@ -24,7 +34,20 @@ export default function useAutoRefresh(refreshAction: () => Promise<void>, timeo
24
34
}
25
35
}
26
36
37
+ /**
38
+ * Updates the timeout interval between refreshes
39
+ * @param updatedTimeout The new time between refreshes in ms or null if no auto-refresh is desired
40
+ */
41
+ async function updateTimeout ( updatedTimeout : number ) {
42
+ timeout . value = updatedTimeout ;
43
+ await executeAndResetTimer ( ) ;
44
+ }
45
+
46
+ // eslint-disable-next-line promise/catch-or-return,promise/prefer-await-to-then,promise/valid-params
47
+ if ( startImmediately ) executeAndResetTimer ( ) . then ( ) ;
48
+
27
49
return {
28
50
executeAndResetTimer,
51
+ updateTimeout,
29
52
} ;
30
53
}
0 commit comments