Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

207
Views
Why does clearInterval and clearTimeout make the self-increment slower?

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>
about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!