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

165
Visualizações
Async calls within setInterval where every next is dependent on previous

I have a setInterval setup which internally calls an API. Based on the api response I manage previousState & currentState variables.

I need to make sure that every next setInterval stuff happens when the previous has updated by variables already.

How can I do it?

let previous = null;
let current = null;

const fakeApi = () => {
  return new Promise((resolve) => setTimeout(resolve(1), 3000));
};

async function fetchData() {
  current = await fakeApi();
  callB(previous, current);
  previous = current;
}

function getStats(cb) {
  setInterval(fetchData, 3000);
}

function callB(prev, curr) {
  console.log(prev + " >>> " + curr);
}

getStats(callB);
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Instead of setInterval, you could create an sleep function and then call the fetchData after its finished

let previous = null;
let current = null;

const fakeApi = () => {
  return new Promise((resolve) => setTimeout(resolve(1), 3000));
};
const sleep = (ms) => new Promise(res => setTimeout(res, ms));

async function fetchData() {
  current = await fakeApi();
  callB(previous, current);
  previous = current;
  await sleep(3000);
  return fetchData()
}


function callB(prev, curr) {
  console.log(prev + " >>> " + curr);
}

getStats(callB);
about 4 years ago · Juan Pablo Isaza Relatório

0

You could add a while loop to repeatedly call the api function:

let previous = null;
let current = null;

const fakeApi = async () => {
   return new Promise(resolve => setTimeout(resolve, 3000));
};


let getStats = async ()=>{
  while(true) {
      await fakeApi()
      callB(previous, current);
      previous = current;
      await new Promise(resolve => setTimeout(resolve, 3000)); //add delay between updates as required
  }
})()


function callB(prev, curr) {
  console.log(prev + " >>> " + curr);
}

getStats();
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