Js being difficult to me >:|
export default function Timer() {
const [timer, setTimer] = useState(10000);
useEffect(() => {
setInterval(() => {
if (Number(timer) > Number(6000)) {
setTimer((prevCount) => prevCount - 100);
}
}, 100);
}, []);
console.log(timer);
Why doesn't this timer stop counting down when it hit 6000?
You wont need setInterval. Let useEffect run only when the timer changes and this is done by passing the timer as argument.
This link describe how to optimize useEffect
const [timer, setTimer] = useState(10000);
function setTimerToNewValue() {
setTimer(timer - 100);
}
useEffect(() => {
if (timer > 6000) {
setTimerToNewValue();
}
}, [timer]);
console.log(timer);
In this example useEffect will execute as soon as timer changes.
Here is another implementation with setInterval
function setTimerToNewValue() {
setTimer((timer) => timer - 100);
}
useEffect(() => {
let z;
if (timer > 6000) {
z = setInterval(() => {
setTimerToNewValue();
}, 1000);
}
return () => clearInterval(z);
}, [timer]);
if you have to use timer you can use this code
export default function Timer() {
const [timer, setTimer] = useState(10000);
useEffect(() => {
console.log(timer)
const interval = setInterval(() => {
if (timer>6000)
setTimer(timer => timer - 1000);
}, 1000);
return () => clearInterval(interval);
})
}