Home > Article > Web Front-end > How to Introduce Delays in Puppeteer: What are the Best Solutions?
Pausing Execution in Puppeteer: Waiting Time Before Proceeding
When working with Puppeteer, it may be necessary to introduce delays before executing subsequent lines of code. However, attempts to utilize the setTimeout function within an evaluate function have often been met with failure.
Solution 1: Using a Promise Function
A simple and effective solution is to employ a promise function, as demonstrated below:
function delay(time) { return new Promise(function(resolve) { setTimeout(resolve, time) }); }
To create a delay, simply call the function with a time argument specifying the desired duration.
console.log('before waiting'); await delay(4000); console.log('after waiting');
Solution 2: Using Puppeteer's waitForTimeout
Puppeteer provides a built-in function called waitForTimeout that can be utilized for this purpose:
await page.waitForTimeout(4000)
Solution 3: Using page.evaluate (Resolved After Time)
While not as straightforward as the previous solutions, it is possible to utilize page.evaluate to handle this task. By resolving the promise after the specified time, a delay can be introduced:
await page.evaluate(async() => { await new Promise(function(resolve) { setTimeout(resolve, 1000) }); });
Conclusion
These methods offer various approaches to introducing delays in Puppeteer, depending on the specific requirements and preferences of the developer.
The above is the detailed content of How to Introduce Delays in Puppeteer: What are the Best Solutions?. For more information, please follow other related articles on the PHP Chinese website!