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

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

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 Denunciar

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