0

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

Stack0verflow
  • 1,148
  • 4
  • 18
  • 42
  • 1
    Promisify the timeouts and `await` them – CertainPerformance May 07 '22 at 03:32
  • That's very smart, even though I have no idea how to do it. But if you don't mind, please share your tweak. Thank you. – Stack0verflow May 07 '22 at 03:34
  • 1
    `const promisifiedTimeout = ms => new Promise(r => setTimeout(r, ms))` ... bang ... now you can `await promisifiedTimeout(1000)` in an `async` function – Bravo May 07 '22 at 03:49
  • I did solve this issue by following the provided answer by @jonas-wilms. Much cleaner than using setTimeout. But, I do need to read more about promise and async functions. – Stack0verflow May 07 '22 at 04:17

0 Answers0