Home >Web Front-end >JS Tutorial >How to Implement a Time Delay in Puppeteer?
Waiting for a Specified Duration in Puppeteer
In Puppeteer, developers occasionally encounter the need to pause execution for a defined period before proceeding to the next line of code. While attempts to incorporate setTimeout within evaluate functions might seem like a viable solution, they often encounter unexpected behavior.
Solutions for Pausing Execution
function delay(time) { return new Promise(function(resolve) { setTimeout(resolve, time) }); }
For instance, to pause for 4 seconds:
console.log('before waiting'); await delay(4000); console.log('after waiting');
await page.waitForTimeout(4000)
await page.evaluate(async() => { await new Promise(function(resolve) { setTimeout(resolve, 1000) }); });
Recommendation
While the evaluate approach can be utilized, the first two methods are generally more straightforward and efficient.
The above is the detailed content of How to Implement a Time Delay in Puppeteer?. For more information, please follow other related articles on the PHP Chinese website!