Recently I had to use an API to automate a process at work. I had to do multiple calls to the same API, but doing so kept causing a 429 error. The API had a limit, I was only allowed to make 1 request per second! Read more to find out how I overcame this hurdle by limiting the amount of requests made to the API.

*In the examples below I will be using NodeJS, taking advantage of the built in async/await functionality alongside the axios package to carry out my API requests. In this example I'll also be using a fake API which can be found at jsonplaceholder.typicode.com, this API does not have a 1 request per second limit.*

The Issue

Take a look at this function below, in this example I'm trying to loop through and get 5 posts from the API.

async function getTodos() {
  
    for(var i = 1; i < 5; i++) {
        const response = await axios.get(`https://jsonplaceholder.typicode.com/todos/${1}`);
    }
  
}

The issue here would be that each request is running as soon as possible after the last one, which will be less than a second since the previous request was made. This will cause an error from the API and the script will break!

The Solution

The way to fix this would be to create a promise-based delay function, like so...

async function getTodos() {

    for(var i = 1; i < 5; i++) {

        if(i > 1) await delay(1000);

        const response = await axios.get(`https://jsonplaceholder.typicode.com/todos/${i}`);
        console.log(response)

    }

    function delay(ms) {
        console.log(`waiting ${ms} miliseconds`)
        return new Promise(resolve => setTimeout(resolve, ms));
    }

}

Now we've added a delay function! This function will tell the loop to wait for 1 second (1000ms) each time it is ran. Great, no longer shall the error appear as we're now waiting for the required amount of time before submitting another request.