Home >Web Front-end >JS Tutorial >How to Implement Delays in Puppeteer: setTimeout vs waitForTimeout?
Delaying Execution in Puppeteer
In Puppeteer, effectively waiting for a specified duration before continuing execution can be achieved through various methods. One common approach is by utilizing the setTimeout function within an evaluate function. However, you may encounter instances where setTimeout seems to be bypassed.
To address this issue, you can implement a custom delay function that utilizes a Promise. Define a function called delay(time), which accepts a time parameter and returns a Promise. Within this function, set up a setTimeout resolver to pause execution for the specified time.
function delay(time) { return new Promise(function (resolve) { setTimeout(resolve, time) }); }
You can then call delay(4000) whenever you wish to introduce a delay of 4 seconds.
console.log('before waiting'); await delay(4000); console.log('after waiting');
Alternatively, Puppeteer provides a built-in waitForTimeout function that simplifies the process. Simply use page.waitForTimeout(4000).
If you insist on using page.evaluate, you can resolve the Promise after the desired delay. The following code demonstrates this approach:
await page.evaluate(async () => { await new Promise(function (resolve) { setTimeout(resolve, 1000) }); });
The above is the detailed content of How to Implement Delays in Puppeteer: setTimeout vs waitForTimeout?. For more information, please follow other related articles on the PHP Chinese website!