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

160
Vistas
using recursion instead of setInterval()

If I want to perform a task at least after 5 seconds then is it a good idea that I use recursion & setTimeOut() instead of setInterval()? I wrote below to achieve this:

let interval=5000;    
function job(){
    let startTime = new Date();
    
    fetchData();//actual task to perform at least after 5 seconds, can take more less or more than 5 seconds
    
    let elaspedTime = (new Date().getTime()) - startTime.getTime();
    let waitTime = (interval * 1000) - elaspedTime;
    if (waitTime > 0) {
        setTimeout(() => {
            job();
        }, waitTime);
    } else {
        job();
    }
}
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You can use a set interval each 5 seconds. Remeber that setInterval returns and Id which you can use, to stop the interval once you got thet data.

function getData(host) {
  // your code
  clearInterval(host.id);
}

var host = {};
host.id = setInterval(getData.bind(null,host),5000);

I used this pattern to have acces in the function to the intervalId. You can read more about this in: Send interval id as an argument to executing function

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can create a promise wait function, and resolve the promise after 5 seconds.

const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const fetchData = () => console.log("===> fetching data");

const job = async () => {
  console.log("===> Job Started");
  await wait(5000);
  console.log("===> Time to Fetch the data");
  fetchData();
};

job();

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