Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

169
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda