I’m having an issue with the auto-increment counter, which updates every 2 secs. It updates the value but in a glitchy way Please check the code and share your views regarding the problem.
JavaScript
x
13
13
1
const [counter, setCounter] = useState(1200)
2
function handleCounter() {
3
setCounter(counter + 1)
4
}
5
useEffect(() => {
6
if (counter => 1200 && counter < 1364) {
7
setInterval(handleCounter, 2000);
8
}else {
9
clearInterval(setInterval(handleCounter, 2000))
10
}
11
clearInterval(setInterval(handleCounter, 2000))
12
}, [counter])
13
Advertisement
Answer
try this
JavaScript
1
10
10
1
useEffect(() => {
2
const timeInterval = setInterval(() => {
3
counter < 1364 && setCounter((prevCount) => prevCount + 1);
4
}, 2000);
5
6
return () => {
7
clearInterval(timeInterval);
8
};
9
}, [counter]);
10