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

199
Views
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
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!