Skip to content

Commit fa0529b

Browse files
committed
feat: enhance useInterval function to support pause and resume controls
1 parent 561eae4 commit fa0529b

File tree

1 file changed

+33
-5
lines changed

1 file changed

+33
-5
lines changed

src/event/useInterval.ts

Lines changed: 33 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,44 @@
11
import { 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
*/
1117
export 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
}

0 commit comments

Comments
 (0)