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);
}
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;
}
}
})
}
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));
}
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)