Simple Countdown
Last active
February 23, 2021 22:43
-
-
Save GGrassiant/8bf881dd4e069675dc12b01091a6d239 to your computer and use it in GitHub Desktop.
Simple countdown
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { useEffect, useRef, useState } from 'react'; | |
| const GIVEN_TIME = 20; | |
| const adjustedTimeInMillis = GIVEN_TIME * 1000 * 60; | |
| const formatTime = (time) => time < 10 ? `0${time}` : time; | |
| const App = () => { | |
| const [millis, setMillis ] = useState(adjustedTimeInMillis); | |
| const minutes = Math.floor(millis / 1000 / 60) % 60; | |
| const seconds = Math.floor(millis / 1000) % 60; | |
| const interval = useRef(null); | |
| const countDown = () => { | |
| setMillis((time) => { | |
| if (time === 0) { | |
| return time | |
| } | |
| const timeLeft = time - 1000; | |
| return timeLeft; | |
| }) | |
| }; | |
| useEffect(() => { | |
| interval.current = setInterval(countDown, 1000); | |
| return () => clearInterval(interval.current); | |
| }, []) | |
| return ( | |
| <div>Coucou: {formatTime(minutes)}:{formatTime(seconds)}</div> | |
| ); | |
| } | |
| export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment