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

161
Views
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 answers
Answer question

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 Report

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