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

462
Visualizações
setTimeout isn't working properly in the while loop

I need it to pause for 3 seconds at the end of every loop, but it's not pausing. How do I fix this? Example codes would be appreciated.

function file_get_contents(url, callback) {
  fetch(url).then(res => res.text()).then(text => callback(text));
}

function theCallBack(text) {
  text = text.replace(/google/g, "")
  let matches = text.match(/www.[a-z\-]+?.com/g);
  console.log(matches[0]);
};

var theArray = ["https://www.google.com/search?q=one", "https://www.google.com/search?q=two", "https://www.google.com/search?q=three"];
var count = theArray.length;

while (count > 0) {
  console.log(count);
  count--;
  file_get_contents(theArray[count], theCallBack);
  setTimeout(function() {}, 3000);
}

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can use a Promise to pause the program and await it.

const wait = (ms) => new Promise(resolve => setTimeout(resolve, ms));


function file_get_contents(url, callback) {
  fetch(url).then(res => res.text()).then(text => callback(text));
}

function theCallBack(text) {
  text = text.replace(/google/g, "")
  let matches = text.match(/www.[a-z\-]+?.com/g);
  console.log(matches[0]);
};

var theArray = ["https://www.google.com/search?q=one", "https://www.google.com/search?q=two", "https://www.google.com/search?q=three"];
var count = theArray.length;



(async() => {
  for (let i = 0; i < count; i++) {
    console.log(i + 1);
    file_get_contents(theArray[i], theCallBack);
    await wait(3000);
  }
})();

about 4 years ago · Juan Pablo Isaza Relatório

0

I think problem is setTineout() async function, so you need make it sync, to work as you want.

https://developer.mozilla.org/ru/docs/Learn/JavaScript/Asynchronous/Timeouts_and_intervals

https://stackoverflow.com/a/50357618

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