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

159
Visualizações
using recursion instead of setInterval()

If I want to perform a task at least after 5 seconds then is it a good idea that I use recursion & setTimeOut() instead of setInterval()? I wrote below to achieve this:

let interval=5000;    
function job(){
    let startTime = new Date();
    
    fetchData();//actual task to perform at least after 5 seconds, can take more less or more than 5 seconds
    
    let elaspedTime = (new Date().getTime()) - startTime.getTime();
    let waitTime = (interval * 1000) - elaspedTime;
    if (waitTime > 0) {
        setTimeout(() => {
            job();
        }, waitTime);
    } else {
        job();
    }
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can use a set interval each 5 seconds. Remeber that setInterval returns and Id which you can use, to stop the interval once you got thet data.

function getData(host) {
  // your code
  clearInterval(host.id);
}

var host = {};
host.id = setInterval(getData.bind(null,host),5000);

I used this pattern to have acces in the function to the intervalId. You can read more about this in: Send interval id as an argument to executing function

about 4 years ago · Juan Pablo Isaza Relatório

0

You can create a promise wait function, and resolve the promise after 5 seconds.

const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const fetchData = () => console.log("===> fetching data");

const job = async () => {
  console.log("===> Job Started");
  await wait(5000);
  console.log("===> Time to Fetch the data");
  fetchData();
};

job();

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