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

162
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 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