How to make API requests with intervals with NodeJS

Viewed 2112

sorry if this question has already been asked, I searched for it but couldn't find anything clear.

How can I make API requests with intervals with NodeJS, for example, one request every 20 seconds?

This so I can respect the API limits, if I make all the requests at once, it'd crash.

Not sure if it matters, but I'm using Axios for the requests.

Please tell me if any other information is needed. Thank you!

3 Answers

It should be easy enough to to this with setInterval, the interval is specified in milliseconds.

If you need more control over when the api is called, e.g. using a cron expression to schedule calls, I'd suggest trying node-cron.

const axios = require("axios");

async function callApi() {
    let response = await axios( { url: "https://jsonplaceholder.typicode.com/users" });
    console.log("Response:", response.data);
} 

function callApiEveryNSeconds(n) {
    setInterval(callApi, n * 1000);
}

callApiEveryNSeconds(20);

This was the best solution to my case:

    let i = 0;
    let idInterval = setInterval(() => {
      if (i < dataFortheAPI.length) {
        funtionThatMakestheApiRequest(dataFortheAPI[i]);
        i++;
      } else {
        clearInterval(idInterval);
      }
    }, 22000);
Related