Home > Web Front-end > JS Tutorial > body text

How to Implement Delays in Puppeteer: setTimeout vs waitForTimeout?

Patricia Arquette
Release: 2024-11-21 11:24:10
Original
391 people have browsed it

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)
    });
}
Copy after login

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');
Copy after login

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)
    });
});
Copy after login

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!

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