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

314
Views
How to wait for function to get executed before the next setinterval call?

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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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.

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!