@@ -3,22 +3,32 @@ import { useState, useEffect } from "react";
33import moment from "moment" ;
44
55function useTimer ( time ) {
6- const [ duration , setDuration ] = useState ( moment ( ) . format ( "HH:mm:ss" ) ) ;
7- const [ seconds , setSeconds ] = useState ( moment ( ) . seconds ( ) ) ;
6+ const [ duration , setDuration ] = useState ( "00:00:00" ) ;
7+ const [ seconds , setSeconds ] = useState ( 0 ) ;
88
99 const updateTimer = ( ) => {
10- if ( seconds >= 0 ) {
11- const diff = moment . utc ( moment . utc ( time ) . local ( ) . diff ( moment ( ) ) ) ;
10+ const targetTime = moment . isMoment ( time )
11+ ? time . clone ( )
12+ : moment . utc ( time , moment . ISO_8601 , true ) ;
1213
13- setDuration ( diff . format ( "HH:mm:ss" ) ) ;
14- setSeconds ( moment . duration ( diff ) . asSeconds ( ) ) ;
14+ if ( ! targetTime . isValid ( ) ) {
15+ setDuration ( "00:00:00" ) ;
16+ setSeconds ( 0 ) ;
17+ return ;
1518 }
19+
20+ const diffMs = Math . max ( targetTime . local ( ) . diff ( moment ( ) ) , 0 ) ;
21+ const diff = moment . utc ( diffMs ) ;
22+
23+ setDuration ( diff . format ( "HH:mm:ss" ) ) ;
24+ setSeconds ( moment . duration ( diffMs ) . asSeconds ( ) ) ;
1625 } ;
1726
1827 useEffect ( ( ) => {
28+ updateTimer ( ) ;
1929 const interval = setInterval ( updateTimer , 77 ) ;
2030 return ( ) => clearInterval ( interval ) ;
21- } ) ;
31+ } , [ time ] ) ;
2232
2333 return [ duration , seconds ] ;
2434}
0 commit comments