Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

155
Views
How to timeout with for loop for ajax request

How can I use for loop with timeout to request ajax every 5 seconds

function req() {
  $.ajax({ .......
  })
}

for (var i = 4000; i <= 6000; i++) {

  setTimeout(function() {
    req(i)
  }, i * 5000);

}
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Don't loop Ajax. If the server is overloaded, you will stack requests that will cancel each other

Instead do

function req() {
  $.ajax({ .......
    success: function() {
      setTimeout(req,5000)
    }
  })
}

If you want to send with 3 different intervals, you can do this

const timeouts = [4000,5000,6000];
let cnt = 0;
function req() {
  $.ajax({ .......
    success: function() {
      setTimeout(req,timouets[cnt]); // move this to an if to stop after 3 calls
      cnt++; if (cnt>= timeouts.length) {
        cnt = 0;
      }
    }
  })
}
about 4 years ago · Juan Pablo Isaza Report

0

You can send the request after every 5s using

time + time * (i - start)

function req(s) {
  console.log("After " + s + "s");
  // $.ajax({.......})
}

const start = 4000,
  end = 6000,
  time = 5000;

for (let i = start; i <= end; i++) {
  setTimeout(function () {
    req((time + time * (i - start)) / 1000); // I've passed the time to track the passed seconds
  }, time + time * (i - start));
}

about 4 years ago · Juan Pablo Isaza Report

0

You can take it as creating a series of time-lapsed requests via for loop.

function req() {
   console.log('requested');
}

for (let i = 1; i <= 10; i++) {
   setTimeout(req, i * 5000)   
}

However, such a series of requests can easily be achieved with setInterval too.

function req(){
   console.log('requested');
}

const limit = 10;
let counter = 1;

let handler = setInterval(function(){
   
   req();
   
   counter++;
   
   if (counter >= limit)
      clearInterval(handler);
   
}, 5000)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!