Calling Multiple API Requests with Delays in JavaScript

January 12, 2023

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!

Reference


👋 I'm Ashik Nesin • Principal Software Engineer 👨‍💻• I write about web development and share insights into the behind-the-scenes of the projects that I'm building.

© 2023 Nesin Technologies LLP