@@ -3,13 +3,22 @@ import { Time, Validate } from './utils';
3
3
import { useInterval } from './hooks' ;
4
4
5
5
const DEFAULT_DELAY = 1000 ;
6
+ function getDelayFromExpiryTimestamp ( expiryTimestamp ) {
7
+ if ( ! Validate . expiryTimestamp ( expiryTimestamp ) ) {
8
+ return null ;
9
+ }
10
+
11
+ const seconds = Time . getSecondsFromExpiry ( expiryTimestamp ) ;
12
+ const extraMilliSeconds = Math . floor ( ( seconds - Math . floor ( seconds ) ) * 1000 ) ;
13
+ return extraMilliSeconds > 0 ? extraMilliSeconds : DEFAULT_DELAY ;
14
+ }
15
+
6
16
export default function useTimer ( { expiryTimestamp : expiry , onExpire, autoStart } ) {
7
17
const [ expiryTimestamp , setExpiryTimestamp ] = useState ( expiry ) ;
8
18
const [ seconds , setSeconds ] = useState ( Time . getSecondsFromExpiry ( expiryTimestamp ) ) ;
9
19
const [ isRunning , setIsRunning ] = useState ( autoStart ) ;
10
20
const [ didStart , setDidStart ] = useState ( autoStart ) ;
11
- const extraMilliSeconds = Math . floor ( ( seconds - Math . floor ( seconds ) ) * 1000 ) ;
12
- const [ delay , setDelay ] = useState ( extraMilliSeconds > 0 ? extraMilliSeconds : 1000 ) ;
21
+ const [ delay , setDelay ] = useState ( getDelayFromExpiryTimestamp ( expiryTimestamp ) ) ;
13
22
14
23
function handleExpire ( ) {
15
24
Validate . onExpire ( onExpire ) && onExpire ( ) ;
@@ -22,19 +31,17 @@ export default function useTimer({ expiryTimestamp: expiry, onExpire, autoStart
22
31
}
23
32
24
33
function restart ( newExpiryTimestamp , newAutoStart = true ) {
25
- const secondsValue = Time . getSecondsFromExpiry ( newExpiryTimestamp ) ;
26
- const extraMilliSecondsValue = Math . floor ( ( secondsValue - Math . floor ( secondsValue ) ) * 1000 ) ;
27
- setDelay ( extraMilliSecondsValue > 0 ? extraMilliSecondsValue : 1000 ) ;
34
+ setDelay ( getDelayFromExpiryTimestamp ( newExpiryTimestamp ) ) ;
28
35
setDidStart ( newAutoStart ) ;
29
36
setIsRunning ( newAutoStart ) ;
30
37
setExpiryTimestamp ( newExpiryTimestamp ) ;
31
- setSeconds ( secondsValue ) ;
38
+ setSeconds ( Time . getSecondsFromExpiry ( newExpiryTimestamp ) ) ;
32
39
}
33
40
34
41
function resume ( ) {
35
42
const time = new Date ( ) ;
36
43
time . setMilliseconds ( time . getMilliseconds ( ) + ( seconds * 1000 ) ) ;
37
- restart ( time , true ) ;
44
+ restart ( time ) ;
38
45
}
39
46
40
47
function start ( ) {
0 commit comments