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

165
Vistas
setInterval triggers a function exponentially

I have a function that changes the value of a string variable to one from a list at set intervals. I figured setInterval would be ideal for this task but It behaves very strangely.

When the program loads, after the first interval delay, it will trigger the function twice, then a couple more times on the next interval. It progressively ramps up until it's triggering the function hundreds of times per interval.

From what I can understand, it's nothing to do with the function itself since I set up a manual trigger for the function and it works normally. (Whenever I call the function manually, it triggers once.)

const [dynString, setDynString] = useState(List[Index]);
setInterval(textTick, 5000);

function textTick(){
        Index = Index + 1;
        if(Index >= List.length){
            Index = 0;
        }
        setDynString(List[Index]);
        console.log('Current String:', Index);
    }

return(
    <div className='text-tick-object'>
        <h1 onClick={textTick}>{dynString}</h1>
    </div>
);
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You should create intervals (side effects in general) inside useEffect() hooks. Any time the component re-renders (when you change the state inside the interval or after a click event) a new interval will start. You only need the interval once, at start

I would suggest something like this:

const list = ["a", "b", "c", "d"];

function MyComponent() {
  const [index, setIndex] = useState(0);

  const textTick = useCallback(() => {
    setIndex((index) => {
      let nextIndex = index + 1;
      if (nextIndex >= list.length) {
        nextIndex = 0;
      }
      console.log("Current String:", nextIndex);
      return nextIndex;
    });
  }, []);

  useEffect(() => {
    const interval = setInterval(textTick, 5000);

    return () => {
      clearInterval(interval);
    };
  }, [textTick]);

  return (
    <div className="text-tick-object">
      <h1 onClick={textTick}>{list[index]}</h1>
    </div>
  );
}

You can see this running in: https://stackblitz.com/edit/react-vn9hxx?file=src/App.js

(it's an external link, might not work in the future, the code is the same)

about 4 years ago · Juan Pablo Isaza 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