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

How to Introduce Delays in Puppeteer Code?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-10 01:39:02389browse

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!

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