1
- import { ref , reactive } from 'vue' ;
1
+ import { ref , reactive , Ref , watch } from 'vue' ;
2
2
import { useRafFn } from '@vueuse/core' ;
3
3
import { TdUseCountDownProps , TdUseCountDown } from './type' ;
4
4
import { getRemainTimes , getShowTimes , getScreenFps } from './utils' ;
5
5
import { isBrowser } from '../util' ;
6
6
7
- export function useCountDown ( props : TdUseCountDownProps ) : TdUseCountDown {
7
+ export function useCountDown ( props : TdUseCountDownProps , visibility ?: Ref < boolean > ) : TdUseCountDown {
8
8
const {
9
9
time = 0 ,
10
10
autoStart,
@@ -18,27 +18,37 @@ export function useCountDown(props: TdUseCountDownProps): TdUseCountDown {
18
18
const fps = ref ( ) ;
19
19
const count = ref ( Number ( time ) ) ;
20
20
const showTimes = reactive ( getShowTimes ( getRemainTimes ( time ) , format , millisecond , splitWithUnit ) ) ;
21
+ let hiddenTime = 0 ;
21
22
22
- // raf
23
- const { pause, resume } = useRafFn (
24
- async ( ) => {
25
- if ( ! isBrowser ) return ;
26
- if ( ! fps . value ) {
27
- const res = await getScreenFps ?.( ) ;
28
- fps . value = res || 60 ;
29
- }
30
- count . value = parseInt ( `${ Number ( count . value ) - 1000 / fps . value } ` , 10 ) ;
31
- if ( count . value <= 0 ) {
32
- pause ?.( ) ;
33
- count . value = 0 ;
23
+ visibility &&
24
+ watch ( visibility , ( val ) => {
25
+ if ( val ) {
26
+ count . value -= Date . now ( ) - hiddenTime ;
27
+ rafFn ( ) ;
28
+ } else {
29
+ hiddenTime = Date . now ( ) ;
34
30
}
35
- const times = getRemainTimes ( count . value ) ;
36
- onChange ?.( times ) ;
37
- count . value === 0 && onFinish ?.( ) ;
38
- getShowTimes ( times , format , millisecond , splitWithUnit ) ?. forEach ?.( ( i , idx ) => ( showTimes [ idx ] . value = i ?. value ) ) ;
39
- } ,
40
- { immediate : autoStart } ,
41
- ) ;
31
+ } ) ;
32
+
33
+ const rafFn = async ( ) => {
34
+ if ( ! isBrowser ) return ;
35
+ if ( ! fps . value ) {
36
+ const res = await getScreenFps ?.( ) ;
37
+ fps . value = res || 60 ;
38
+ }
39
+ count . value = parseInt ( `${ Number ( count . value ) - 1000 / fps . value } ` , 10 ) ;
40
+ if ( count . value <= 0 ) {
41
+ pause ?.( ) ;
42
+ count . value = 0 ;
43
+ }
44
+ const times = getRemainTimes ( count . value ) ;
45
+ onChange ?.( times ) ;
46
+ count . value === 0 && onFinish ?.( ) ;
47
+ getShowTimes ( times , format , millisecond , splitWithUnit ) ?. forEach ?.( ( i , idx ) => ( showTimes [ idx ] . value = i ?. value ) ) ;
48
+ } ;
49
+
50
+ // raf
51
+ const { pause, resume } = useRafFn ( rafFn , { immediate : autoStart } ) ;
42
52
43
53
/**
44
54
* return
0 commit comments