Published on

Calling Single API Multiple Times with Delay in JavaScript

Authors

Sometime, you might want to execute a single API request multiple times. And also want add some delay between then to avoid getting it blocked.

Here is an example a little snippet on how to do it

function delay(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

const createUser = (id) => {
 return fetch("https://httpbin.org/post", {
  method: "POST",
  headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
  },
  body:JSON.stringify({"id":id})
});
} 
async function runPromises() {
    for (let i = 1; i < 50; i++) {
        await createUser(`user_id_${i}`);
        await delay(3000); // 3s
    }
}

runPromises()

Happy multiple promises!