Home > Web Front-end > JS Tutorial > How to Introduce Delays in Puppeteer Code?

How to Introduce Delays in Puppeteer Code?

Mary-Kate Olsen
Release: 2024-11-10 01:39:02
Original
399 people have browsed it

How to Introduce Delays in Puppeteer Code?

Creating Delays in Puppeteer Code

In Puppeteer, it may be necessary to introduce intentional delays before executing subsequent code lines. To address this, you can opt for one of the following solutions:

Using a Promise Function

For flexible and independent delays, consider utilizing a simple promise function:

function delay(time) {
   return new Promise(function(resolve) { 
       setTimeout(resolve, time)
   });
}
Copy after login

To implement the delay, make the following changes:

console.log('before waiting');
await delay(4000);
console.log('after waiting');
Copy after login

Using Puppeteer's Built-in Function

If you prefer to stay within the Puppeteer environment, take advantage of the built-in waitForTimeout function:

await page.waitForTimeout(4000)
Copy after login

This function will effectively pause code execution for the specified number of milliseconds.

Using Evaluated Promises

If you still prefer to use page.evaluate, you can modify your current code to resolve the promise after the desired delay:

await page.evaluate(async() => {
    await new Promise(function(resolve) { 
           setTimeout(resolve, 1000)
    });
});
Copy after login

However, this approach may not be as practical as the first two methods due to its potential for overcomplication.

The above is the detailed content of How to Introduce Delays in Puppeteer Code?. 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