I made a web scraping script using the NodeJS Puppeteer package (v21.1.1) based on TypeScript.
I used await page.waitForTimeout(3000); method to delay the script running until page loading. This function works but it has the following issue:
The signature '(milliseconds: number): Promise<void>' of 'page.waitForTimeout' is deprecated.ts(6387)
types.d.ts(5724, 8): The declaration was marked as deprecated here.
I want to use an alternative instead of using a deprecated function.
The best solution is not to use it, because arbitrary sleeps are slow and unreliable. Prefer event-driven predicates like locators, waitForSelector, waitForFunction, waitForResponse, etc. See this post for details.
That said, if you need to sleep to help debug code temporarily, or you're writing a quick and dirty script which doesn't need to be reliable, you can use a plain Node wait:
import {setTimeout} from "node:timers/promises";
// ...
await setTimeout(3000);
Also possible is promisifying setTimeout yourself, which is useful if you're sleeping in the browser context:
const sleep = ms => new Promise(res => setTimeout(res, ms));
(async () => {
console.log(new Date().getSeconds());
await sleep(3000);
console.log(new Date().getSeconds());
})();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With