Home  >  Article  >  Web Front-end  >  How to Introduce Delays in Puppeteer: What are the Best Solutions?

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

Patricia Arquette
Patricia ArquetteOriginal
2024-11-13 14:59:02597browse

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!

Statement:
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