Ask Your Question

What is the approach to setInterval for running multiple ajax requests simultaneously?

asked 2021-10-16 11:00:00 +0000

bukephalos gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2022-09-20 18:00:00 +0000

devzero gravatar image

One approach to running multiple ajax requests simultaneously with setInterval is to create an array of all the requests that need to be made, then use a loop to iterate through the array and make the requests using setInterval. Each request can be made using the XMLHttpRequest object and a callback function can be used to handle the response. Here is an example code snippet:

// Define an array of requests
var requests = [
  {url: '', method: 'GET'},
  {url: '', method: 'POST', data: {user_id: 123}}

// Define a function to make a single request
function makeRequest(request, callback) {
  var xhr = new XMLHttpRequest();, request.url);
  xhr.onload = function() {
    if (xhr.status === 200) {

// Define a function to make all requests in the array
function makeRequests() {
  for (var i = 0; i < requests.length; i++) {
    makeRequest(requests[i], function(response) {
      console.log(response); // Handle the response for each request

// Call the makeRequests function every 5 seconds using setInterval
setInterval(makeRequests, 5000);

In this example, the requests array has two objects representing two separate requests. The makeRequest function takes a request object and a callback function as arguments and uses XMLHttpRequest to make the request. The makeRequests function uses a loop to iterate over the array, calls makeRequest for each request, and passes in a callback function to handle the response. Finally, the setInterval function is used to call the makeRequests function every 5 seconds.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer

Question Tools


Asked: 2021-10-16 11:00:00 +0000

Seen: 7 times

Last updated: Sep 20 '22