Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix issue that deprecated 'page.waitForTimeout' method usage

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.

like image 851
Dev Conductor Avatar asked Nov 28 '25 05:11

Dev Conductor


1 Answers

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());
})();
like image 163
ggorlen Avatar answered Nov 30 '25 20:11

ggorlen