1import React from 'react'
2import { useState, useEffect } from 'react';
3
4const Timer = (props:any) => {
5 const {initialMinute = 0,initialSeconds = 0} = props;
6 const [ minutes, setMinutes ] = useState(initialMinute);
7 const [seconds, setSeconds ] = useState(initialSeconds);
8 useEffect(()=>{
9 let myInterval = setInterval(() => {
10 if (seconds > 0) {
11 setSeconds(seconds - 1);
12 }
13 if (seconds === 0) {
14 if (minutes === 0) {
15 clearInterval(myInterval)
16 } else {
17 setMinutes(minutes - 1);
18 setSeconds(59);
19 }
20 }
21 }, 1000)
22 return ()=> {
23 clearInterval(myInterval);
24 };
25 });
26
27 return (
28 <div>
29 { minutes === 0 && seconds === 0
30 ? null
31 : <h1> {minutes}:{seconds < 10 ? `0${seconds}` : seconds}</h1>
32 }
33 </div>
34 )
35}
36
37export default Timer;
1function App() {
2 const [seconds, setSeconds] = React.useState(10);
3
4 React.useEffect(() => {
5 if (seconds > 0) {
6 setTimeout(() => setSeconds(seconds - 1), 1000);
7 } else {
8 setSeconds('BOOOOM!');
9 }
10 });
11
12 return (
13 <div className="App">
14 <div>
15 {seconds}
16 </div>
17 </div>
18 );
19}