2

I need a way to add some delay between clicking elements inside a page.evaluate function

below is what ive tried and it does not work

const result = await page.evaluate(async () => {
        let variants = document.querySelectorAll(".item-sku-image a");


        variants.forEach(async variant => {   
           await new Promise(function(resolve) { 
           setTimeout(resolve, 1000)
           });         
            await variant.click()
        });
        return data
    });

Update:

the for loop below works fine for one element when i try to use another for loop inside it - it goes crazy

const variants = [...document.querySelectorAll(".item-sku-image a")]; // Turn nodelist into an array
const sizes = [...document.querySelectorAll(".item-sku-size a")]; // Turn nodelist into an array

for (let variant of variants){
  // wait one second
  await new Promise(function(resolve) {setTimeout(resolve, 1000)});
  await variant.click()
  for (let size of sizes){
   // wait one second
   await new Promise(function(resolve) {setTimeout(resolve, 1000)});
   await size.click()
 }
}
Limpfro
  • 147
  • 6
  • 12

1 Answers1

6

.forEach will not work with the promises or async...await the way you want.

Use for..of instead.

const variants = [...document.querySelectorAll(".item-sku-image a")]; // Turn nodelist into an array
for (let variant of variants){
  // wait one second
  await new Promise(function(resolve) {setTimeout(resolve, 1000)});
  await variant.click()
}

It's easy to read, understand and implement.

Here are some references:

Md. Abu Taher
  • 17,395
  • 5
  • 49
  • 73
  • second problem for each variant elements i need to click all elements of sizes when i run another for loop inside this for loop i get some really weird behavior. – Limpfro May 14 '19 at 13:51
  • What weird behavior do you get? – Md. Abu Taher May 14 '19 at 14:52
  • first all the variants are clicked till the end - then all the sizes are clicked till the end it should click the first variant then click all sizes then repeat all over again (logically) – Limpfro May 14 '19 at 15:01