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

122
Visualizações
Different intervals for setTimeout in useEffect

I am trying to achieve a situation when a function inside setTimeout is executed after X seconds first time, and then regularly at Y interval.

    useEffect(() => {
    let firstTime = true;
    const timer = setTimeout(() => {
      getValue(id).then((res) => {
        setValue(res);
      });
      if (firstTime) {
        firstTime = false;
      }
    }, firstTime ? 30000 : 60000);
    return () => clearTimeout(timer);
  }, [])

This doesn't work, however, as it sets firstTime to false before running the function. Is there a way to graciously achieve the result? Is it even possible with setTimeout?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can use a variable as the setTimeout delay. In this case you would set firstTime to the delay you wanted to use the first time (30000), and then inside timer you would use if (firstTime == 30000) { firstTime = 60000; }. Using a different variable name here would make sense. Then set the setTimeout delay to just firstTime like }, firstTime);

Hopefully this is actually what you wanted.

useEffect(() => {
    let firstTime = 30000;
    const timer = setTimeout(() => {
      getValue(id).then((res) => {
        setValue(res);
      });
      if (firstTime == 30000) {
        firstTime = 60000;
      }
    }, firstTime);
    return () => clearTimeout(timer);
  }, [])

Old (incorrect) answer:

You can use setTimeout with an initial delay to initialise a setInterval, which will repeat subsequent times at a different interval.

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