Home > Software engineering >  using recursion instead of setInterval()
using recursion instead of setInterval()

Time:06-25

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

CodePudding user response:

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

CodePudding user response:

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

  • Related