Skip to content

Instantly share code, notes, and snippets.

@bautistaaa
Created October 1, 2020 07:16
Show Gist options
  • Save bautistaaa/d2cb82649fe4341551c9eaf6534b754c to your computer and use it in GitHub Desktop.
Save bautistaaa/d2cb82649fe4341551c9eaf6534b754c to your computer and use it in GitHub Desktop.
import React, { useState, useEffect, useRef } from "react";
const TimerFunction = ({ minutes, seconds }) => {
const [min, setMin] = useState(minutes);
const [sec, setSec] = useState(seconds);
const [active, setActive] = useState(false);
const intervalRef = useRef();
useEffect(() => {
setMin(minutes);
}, [minutes]);
useEffect(() => {
setSec(seconds);
}, [seconds]);
// 3 20s
// 60000 * 3 + 20000 -- 182000
useEffect(() => {
if (active) {
intervalRef.current = setInterval(() => {
setMin(min => {
if (min > 0) {
return min - 1;
}
return min;
});
setSec(sec => {
if (sec > 0) {
return sec - 1;
}
return sec;
});
}, 1000);
} else {
clearInterval(intervalRef.current);
}
// return () => clearInterval(interval);
}, [active, minutes, seconds]);
// var min = Math.floor(timeLeft / 6000).toFixed(0);
// var sec = timeLeft % 60;
// const startStop = e => {
// e.preventDefault();
// if (!active) {
// setActive(true);
// } else {
// setActive(false);
// }
// };
return (
<div style={{ display: "flex" }}>
<p>{min}</p>
<p>:</p>
<p>{sec}</p>
<button onClick={() => setActive(!active)}>
{active === true ? "Stop" : "Start"}
</button>
</div>
);
};
export default TimerFunction;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment