Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

161
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!