Reputation: 119
It works well as I was able to stop when the certain limit is being met through the iteration.
But I wonder why when I tried to delay the time of execution of setInterval, the increment of progressBar becomes slower.
Increasing the delay time of either setInterval or setTimeout would affect the speed to slower.
What I wanted is delay the execution by 5 secs, and the increment speed is 1 per second.
const [progressBar, setProgressBar] = React.useState(0);
let timeout;
let interval;
React.useEffect(
() => {
timeout = setTimeout(() =>{
if(progressBar === 100){
return clearTimeout(timeout);
} else{
interval = setInterval(() =>{
if(progressBar === 100){
clearInterval(interval);
} else{
setProgressBar(prev_value => prev_value + 1);
}
},10);
}
}, 10);
return () => {
clearTimeout(timeout);
clearInterval(interval);
};
}, [progressBar]);
let divStyle = {
backgroundColor: "green",
width: "100px",
maxWidth: `${progressBar}px`,
border: "1px solid red"
}
JSX
<div className='progress-bar' style={divStyle}>{progressBar}</div>
Upvotes: 1
Views: 255
Reputation: 13
I think you use hook error, if you using setState inside react, that will be re exec that function again in react world.
so your interval always run 1 time cause you destory that in destroy call back,
once you setState that will be triggered based on your useEffect
deps,
I think you should write that like that. not need any deps and only clear that interval when that value become what you want.
maybe that will be helpful. https://stackblitz.com/edit/react-ts-any9su?file=App.tsx
Upvotes: 0