Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

198
Vistas
setTimeout in nested for loops in JavaScript not working like what I want

I am writing a JavaScript application to simulate a document download process in web automation. The page to interact has a paginated list of people like shown in the screenshot below. Clicking on the person's name will download this person's document.

The automation process downloads each person's document, then proceeds to the next page and continues to download in the same way.

I would like (1) a 2 second delay between each download and (2) a 2 second delay after hitting a new page and before the first download.

After some research, I came up with the following. It is very close to what I want except that it executes the download immediately after landing on the next page. Any idea on how I can tweak it to get a 2+ seconds of delay between landing on a new paginated page and the first download?

function downloadDoc(x)
{
  console.log("Downloading doc ", x);
}

function goToPage(p)
{  
  
   for(let i=0; i<5; i++) 
   {
      setTimeout(downloadDoc, i*2000, i);
   }

      console.log("Go to page ", p);  
}


for(let i=0; i<5; i++) 
{
   setTimeout(downloadDoc, i*2000, i);
}

for (let p = 2; p< 5; p++) 
{    
  setTimeout(goToPage, p * 12000, p);
}

UPDATE: Solved by following the provided answer by @jonas-wilms at https://stackoverflow.com/a/44476626/97109

async function downloadDoc(x)
{
  await timer (1000);
  console.log("Downloading doc ", x);
}

async function goToPage(p) 
{
    await timer(2000);
    console.log("Go to page ", p);
}


async function task(i) { // 3
  await timer(1000);
  //console.log(` ${i} done!`);
    downloadDoc(i);
}

async function main() {
  for(let i = 0; i < 8; i++) {
       await goToPage(i);
      
    for(let j = 0; j < 5; j++) {
        await task(j);

        if (j === 4) { 
          await timer(2000);
        }
    }
  }
}
    
main();

function timer(ms) { return new Promise(res => setTimeout(res, ms)); }

enter image description here

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda