File tree Expand file tree Collapse file tree 1 file changed +33
-5
lines changed
Expand file tree Collapse file tree 1 file changed +33
-5
lines changed Original file line number Diff line number Diff line change 11import { isFn } from '../is/isFn'
22
3- type UseIntervalReturn < T > = T extends Function ? ( ) => void : undefined
3+ interface UseIntervalControls {
4+ isActive : ( ) => boolean
5+ pause : ( ) => void
6+ resume : ( ) => void
7+ }
8+
9+ type UseIntervalReturn < T > = T extends Function ? UseIntervalControls : undefined
410
511/**
6- * setInterval
12+ * 可暂停和恢复的 setInterval
713 * @param { Function } fn 函数
814 * @param { number } duration 间隔时间
9- * @returns 停止
15+ * @returns { { isActive: () => boolean; pause: () => void; resume: () => void } | undefined }
1016 */
1117export function useInterval < T > ( fn : T , duration : number ) : UseIntervalReturn < T > {
1218 if ( ! isFn ( fn ) )
1319 return undefined as any
14- const timer = setInterval ( fn , duration )
15- return ( ( ) => clearInterval ( timer ) ) as any
20+
21+ let timer : number | null = null
22+ let _isActive = false
23+
24+ const controls : UseIntervalControls = {
25+ isActive : ( ) => _isActive ,
26+ pause : ( ) => {
27+ if ( timer ) {
28+ clearInterval ( timer )
29+ timer = null
30+ _isActive = false
31+ }
32+ } ,
33+ resume : ( ) => {
34+ if ( timer )
35+ return
36+ timer = setInterval ( fn as Function , duration )
37+ _isActive = true
38+ } ,
39+ }
40+
41+ controls . resume ( )
42+
43+ return controls as any
1644}
You can’t perform that action at this time.
0 commit comments