1- import { useState , useEffect } from 'react' ;
1+ import { useState } from 'react' ;
22import { Time , Validate } from './utils' ;
33import { useInterval } from './hooks' ;
44
55export default function useTimer ( { expiryTimestamp : expiry , onExpire, autoStart } ) {
66 const [ expiryTimestamp , setExpiryTimestamp ] = useState ( expiry ) ;
77 const [ seconds , setSeconds ] = useState ( Time . getSecondsFromExpiry ( expiryTimestamp ) ) ;
8- const [ isRunning , setIsRunning ] = useState ( false ) ;
8+ const [ isRunning , setIsRunning ] = useState ( autoStart ) ;
9+ const [ didStart , setDidStart ] = useState ( autoStart ) ;
910
1011 function handleExpire ( ) {
1112 Validate . onExpire ( onExpire ) && onExpire ( ) ;
@@ -15,17 +16,22 @@ export default function useTimer({ expiryTimestamp: expiry, onExpire, autoStart
1516 setIsRunning ( false ) ;
1617 }
1718
18- function start ( ) {
19- setIsRunning ( true ) ;
20- }
21-
2219 function resume ( ) {
2320 const time = new Date ( ) ;
2421 time . setSeconds ( time . getSeconds ( ) + seconds ) ; // calculate new expiry timestamp based on last paused seconds count
2522 setExpiryTimestamp ( time ) ;
2623 setIsRunning ( true ) ;
2724 }
2825
26+ function start ( ) {
27+ if ( didStart ) {
28+ setIsRunning ( true ) ;
29+ } else {
30+ resume ( ) ;
31+ setDidStart ( true ) ;
32+ }
33+ }
34+
2935 function restart ( newExpiryTimestamp ) {
3036 setExpiryTimestamp ( newExpiryTimestamp ) ;
3137 setSeconds ( Time . getSecondsFromExpiry ( newExpiryTimestamp ) ) ;
@@ -39,12 +45,6 @@ export default function useTimer({ expiryTimestamp: expiry, onExpire, autoStart
3945 setSeconds ( secondsValue ) ;
4046 } : ( ) => { } , 1000 ) ;
4147
42- useEffect ( ( ) => {
43- if ( autoStart ) {
44- setIsRunning ( true ) ;
45- }
46- } , [ autoStart ] ) ;
47-
4848 return {
4949 ...Time . getTimeFromSeconds ( seconds ) , start, pause, resume, restart, isRunning,
5050 } ;
0 commit comments