Recently, I've been using Puppeteer in my latest project. I installed the library using NPM. According to the documentation, I learned that the page.waitFor() function is now deprecated and has been replaced by page.waitForTimeout(). However, when I attempted to use the new function, I encountered an error: "UnhandledPromiseRejectionWarning: TypeError: page.waitForTimeout is not a function."

Here's a detailed solution to the "Puppeteer waitForTimeout is not a function" error, along with an example code snippet:

Solution to "Puppeteer waitForTimeout is not a function"

This error typically occurs when using Puppeteer, a Node library which provides a high-level API over the Chrome DevTools Protocol, and attempting to call the waitForTimeout function which does not exist in Puppeteer.

Reason:

The most common cause of this error is confusion with another similar function named waitFor, which is used to wait for certain conditions to be met on a page, but not for waiting a specific amount of time.

Solution:

To resolve this error, you need to use the correct function for waiting a specific amount of time in Puppeteer, which is setTimeout or wait


    const puppeteer = require('puppeteer');

    (async () => {
      const browser = await puppeteer.launch();
      const page = await browser.newPage();
      
      // Example of waiting for 2000 milliseconds (2 seconds)
      await page.waitForTimeout(2000); // Incorrect, will cause error
      
      // Correct usage: 
      await page.waitForTimeout(2000); // Wait for 2000 milliseconds

      await browser.close();
    })();
  

In this example, we replaced the incorrect waitForTimeout with setTimeout, which is the correct function in Puppeteer for waiting a specified amount of time.

Alternatively, you can also use await page.waitFor(2000) to wait for a specific condition to be met, instead of waiting for a fixed amount of time.

Additionally, I want to share that page.waitForTimeout was introduced in Puppeteer version 5.3.0. If you're using a version earlier than this, you won't be able to utilize this new function. Since older versions of Puppeteer lack waitForTimeout and versions>=22 have removed the method, an alternative approach is required.

One workaround is to use a vanilla Node sleep:

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

If you're working with a very old version of Node that doesn't support timers/promises, you can manually promisify setTimeout. This is a useful pattern to be aware of, especially since it's compatible with browser environments as well.