Home > Web Front-end > JS Tutorial > body text

How to Introduce Delays in Puppeteer: What are the Best Solutions?

Patricia Arquette
Release: 2024-11-13 14:59:02
Original
596 people have browsed it

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)
   });
}
Copy after login

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');
Copy after login

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)
Copy after login

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)
    });
});
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template