Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

157
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda