Home > Mobile >  How to wait for function to get executed before the next setinterval call?
How to wait for function to get executed before the next setinterval call?

Time:05-16

Lets say I am calling an API that gives me the information about a particular movie according to its id.

I have a function to make an API call:

async function main() { 
 const movieDetails = await getMovieInfo(movieID)
}

setInterval(main,1000*2)

The API call takes some time to return the movie data, lets say 10 seconds ( this time can of course be variable ) . Now how do I wait for the API to get called before the next main function call?

CodePudding user response:

Instead of setInterval, use a recursive function with setTimeout

const getMovieInfo = (movieID) => fetch(`https://jsonplaceholder.typicode.com/posts/${movieID}`)
  .then(res => res.json())
  .catch(err => { console.log(err) });

const loopGetMovie = async () => {
  const movieDetails = await getMovieInfo(34); // Await for response...
  console.log(movieDetails);
  setTimeout(loopGetMovie, 2000); // then timeout a next recursion
};


const main = () => { 
  loopGetMovie();
  // Other "main" function calls here...
};

// Init:
main();

CodePudding user response:

If you really want setInterval(), you could add another condition to check if it's time to getMoveInfo:

let running = false;

async function main() { 
  if (running) return;
  running = true;
  const movieDetails = await getMovieInfo(movieID)
  running = false;
}

setInterval(main, 1000*2)

Although I'd agree that the proposed setTimeout is a much better solution.

  • Related