Skip to content

Instantly share code, notes, and snippets.

@bbachi
Created April 10, 2021 02:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bbachi/73afd46e3ac356866b41c192138644b5 to your computer and use it in GitHub Desktop.
Save bbachi/73afd46e3ac356866b41c192138644b5 to your computer and use it in GitHub Desktop.
REACT
import React from 'react'
const CountDownTimer = ({hoursMinSecs}) => {
const { hours = 0, minutes = 0, seconds = 60 } = hoursMinSecs;
const [[hrs, mins, secs], setTime] = React.useState([hours, minutes, seconds]);
const tick = () => {
if (hrs === 0 && mins === 0 && secs === 0)
reset()
else if (mins === 0 && secs === 0) {
setTime([hrs - 1, 59, 59]);
} else if (secs === 0) {
setTime([hrs, mins - 1, 59]);
} else {
setTime([hrs, mins, secs - 1]);
}
};
const reset = () => setTime([parseInt(hours), parseInt(minutes), parseInt(seconds)]);
React.useEffect(() => {
const timerId = setInterval(() => tick(), 1000);
return () => clearInterval(timerId);
});
return (
<div>
<p>{`${hrs.toString().padStart(2, '0')}:${mins
.toString()
.padStart(2, '0')}:${secs.toString().padStart(2, '0')}`}</p>
</div>
);
}
export default CountDownTimer;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment