'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);


Solution 1:[1]

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

Solution 2:[2]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 bill.gates
Solution 2