Home >Web Front-end >JS Tutorial >How to Implement a Time Delay in Puppeteer?

How to Implement a Time Delay in Puppeteer?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-17 05:08:03715browse

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

  1. Promise-Based Delay: A simple and effective method is to define a delay function as a promise and then invoke it whenever a pause is desired.
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');
  1. page.waitForTimeout: Puppeteer provides a built-in function specifically designed for waiting.
await page.waitForTimeout(4000)
  1. Resolved Evaluate: If the page.evaluate function is preferred, it's crucial to resolve the promise after the desired delay has elapsed.
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!

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