Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

puppeteer: wait N seconds before continuing to the next line

In puppeteer I would like to wait a defined time before going to the next line of code.

I've tried to put a setTimeout in an evaluate function but it seems to be simply ignored

console.log('before waiting'); await page.evaluate(async() => {   setTimeout(function(){       console.log('waiting');   }, 4000) }); console.log('after waiting'); 

This code don't wait and just write before waiting and after waiting

Do you know how to do this?

like image 225
Pipo Avatar asked Oct 24 '17 19:10

Pipo


People also ask

How do you use a puppeteer to click a button?

How to click on a button using puppeteer. click() is used to click on any element or button in the puppeteer. the only challenging thing with this is finding the element. Once you got the element just fire the click() function.


1 Answers

You can use a little promise function,

function delay(time) {    return new Promise(function(resolve) {         setTimeout(resolve, time)    }); } 

Then, call it whenever you want a delay.

console.log('before waiting'); await delay(4000); console.log('after waiting'); 

If you must use puppeteer use the builtin waitForTimeout function.

await page.waitForTimeout(4000) 

If you still want to use page.evaluate, resolve it after 4 seconds. You are not resolving anything.

await page.evaluate(async() => {     await new Promise(function(resolve) {             setTimeout(resolve, 1000)     }); }); 

But I guess you can simply use the first two examples.

like image 80
Md. Abu Taher Avatar answered Sep 29 '22 03:09

Md. Abu Taher