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

219
Views
How to sleep between each axios call in react

I'm writing an app that needs to query an RestAPI with a set of input. However, that API is very bad at scaling and it will return code 429 if it receives too many request. So I was trying to add a sleep function between each axios call but it seems not working. Wondering if I have this sleep function set correctly.

const sleep = (milliseconds) => {
    return new Promise(resolve => setTimeout(resolve, milliseconds))
}


useEffect(() => {
    let results = [];
    
    async function fetchData(id) {
        let request = someAPI + id + query;
        axios.get(request).then((result) => {
            results.push(result);
        }).catch((error) => {console.log(error);});
        await sleep(2000);
    }

    for (let i = 1; i <= 20; i++) {
        fetchData(i);
    }
    
},[]);

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

0

You didn't await the fetchData function, you can try this.

useEffect(() => {
  let results = [];

  async function fetchData(id) {
    try {
       const result = await axios.get('')
       results.push(result);
       await sleep(2000)
    }
    catch(error) {
       console.log(error);
    }
  }

 (async function() {
   for (let i = 1; i <= 20; i++) {
     await fetchData(i);
   }
 })()


},[]);
about 4 years ago · Juan Pablo Isaza Report

0

In your for loop, you have to await the fetchData function. This way, for each iteration, the process will wait for fetchData (and therefore the nested call to the sleep function) to complete.

Currently, you're just firing off all 20 calls to fetchData at once, without actually waiting for your sleep function.

async function fetchAll() {
  for (let i = 0; i < 20; i++) {
    await fetchData()
  }
}

fetchAll()

Note that you will have to wrap your for-loop in an async function, in order to be able to use await within the loop.

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!