Skip to content

Instantly share code, notes, and snippets.

@GGrassiant
Last active February 23, 2021 22:43
Show Gist options
  • Select an option

  • Save GGrassiant/8bf881dd4e069675dc12b01091a6d239 to your computer and use it in GitHub Desktop.

Select an option

Save GGrassiant/8bf881dd4e069675dc12b01091a6d239 to your computer and use it in GitHub Desktop.
Simple countdown
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