Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

210
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda