Home >Web Front-end >JS Tutorial >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) }); }
To implement the delay, make the following changes:
console.log('before waiting'); await delay(4000); console.log('after waiting');
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)
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) }); });
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!