I made a web scraping script using the NodeJS puppeteer package 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.

2

1 Answer

The best solution is not to use it, because arbitrary sleeps are slow and unreliable. Prefer event-driven predicates like 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 hack script which doesn't need to be reliable, just use a plain Node wait:

import {setTimeout} from "node:timers/promises"; // ... await setTimeout(3000); 

Also possible is promisifying setTimeout yourself:

const sleep = ms => new Promise(res => setTimeout(res, ms)); (async () => { console.log(new Date().getSeconds()); await sleep(3000); console.log(new Date().getSeconds()); })();
1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.