October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk4 min

How to Wait for a JavaScript Condition in Puppeteer

Learn when to use Puppeteer’s waitForFunction, waitForSelector, or locators, with examples for page conditions, visibility, timeouts, cancellation, and debugging.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use Puppeteer’s page.waitForFunction() when you need to wait for an arbitrary JavaScript condition in the page to become true. For an element’s presence or visibility, use page.waitForSelector(); for a condition tied to an element interaction, prefer a locator. The official Puppeteer documentation reviewed for this article is marked version 25.12.0, so check your installed version if its API differs.

Wait for a general JavaScript condition with waitForFunction()

page.waitForFunction() repeatedly evaluates a function in the browser page context and resolves when its result is truthy. Use a predicate that checks the specific application state you need—not merely that some time has passed.

await page.waitForFunction(() => {
  const status = document.querySelector('[data-status]');
  return status?.textContent === 'Ready';
});

The callback runs in the page, where it can inspect the DOM and page globals. It does not automatically close over variables from your Node.js script. Pass Node-side values as arguments after the options object:

const selector = '.result';

await page.waitForFunction(
  selector => Boolean(document.querySelector(selector)),
  {},
  selector,
);

The page function may also be asynchronous. Because Puppeteer evaluates the condition repeatedly, keep the predicate focused on observation; do not put an action in it that should happen only once.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose the wait that matches the condition

What must become true Use What it does
A general browser-side value or predicate becomes truthy page.waitForFunction(fn, options, ...args) Evaluates a page-context function until it returns a truthy result.
A matching selector appears in the DOM page.waitForSelector(selector) Resolves when the element exists, including if it already exists when the wait begins.
A matching element must be visible or hidden page.waitForSelector(selector, { visible: true }) or { hidden: true } Expresses the visibility requirement directly. Hidden waits can resolve with null if the selector is absent.
A condition should control an element interaction page.locator(...) Locators are Puppeteer’s documented recommended interface for selecting and interacting with elements, and can wait on a function-based condition.

Wait for element presence, visibility, or an interaction precondition

Selector presence or visibility

Use waitForSelector() when the condition is simply that a selector matches. By default, it waits for DOM presence, not visibility. Set visible: true to require that the element is present and visible, or hidden: true to wait until it is absent or hidden.

const result = await page.waitForSelector('.result', { visible: true });

When found, the method returns an ElementHandle. The documented default timeout is 30,000 ms; set timeout: 0 to disable the timeout. For a hidden wait, the result can be null when the selector is absent.

Locator conditions and actions

Use a locator when the wait is part of selecting or interacting with an element. A locator can use a function that returns a value only once the required condition is met:

const paragraphs = await page
  .locator(() => {
    const items = document.querySelectorAll('p');
    if (items.length >= 3) {
      return [...items].map(item => item.textContent);
    }
  })
  .wait();

This example waits for at least three paragraphs and then returns their text. If you use waitForSelector() and keep the resulting handle, dispose of the ElementHandle when you no longer need it.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Set a timeout or cancel a wait

Waits use a 30-second default timeout in the documented API. For an individual wait, provide a method-level timeout; to change the page-wide default, use Page.setDefaultTimeout(). The wait options also accept an AbortSignal so your code can cancel a pending wait.

await page.waitForFunction(
  () => window.appState?.ready === true,
  { timeout: 10_000 },
);

Use timeout: 0 only when an unbounded wait is intentional. If the condition never becomes true, a wait without a timeout can leave the script hanging.

Troubleshoot a condition that times out

  • The predicate never becomes truthy: Check that the expected state is actually reached on this page and that the predicate matches its real value, spelling, and type.
  • The callback reads the wrong scope: Remember that the callback executes in the browser. Pass needed Node.js values as arguments instead of referencing local variables as though the callback closed over them.
  • The selector exists but the wait still fails: Confirm that the selector is correct and that the condition is not stricter than intended. A default selector wait requires presence, while { visible: true } also requires visibility.
  • The wait ends later than expected: Check the method-level timeout and any page-wide default set with Page.setDefaultTimeout(). A 30-second default applies unless configured otherwise.
  • The operation can be cancelled: Supply an AbortSignal through the wait options and trigger its cancellation from the calling code.

Prefer a condition wait over a fixed sleep when the requirement is a state change: the wait represents the actual condition and can finish as soon as it passes.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If you only need a screenshot rather than Puppeteer control over a custom condition, ScreenshotNeo provides a website screenshot API and MCP server. It accepts a URL in one GET request and returns an image or PDF; it is not a replacement for waiting on arbitrary page state in your own Puppeteer workflow.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
The SQL Programming Language: .
  • Used Book in Good Condition
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the ScreenshotNeo API documentation for request options. It removes cookie banners, popups, and chat widgets before the shot; bot checks, blank pages, and failed loads are never billed. Its MCP server lets AI agents take screenshots. The Free plan includes 1,000 screenshots per month without a card, and paid plans start at $5 for 3,000.

Sign up for ScreenshotNeo free to get 1,000 screenshots a month with no card.

Frequently Asked Questions

Does waitForFunction() check the page or the Node.js process?

It evaluates its callback in the browser page context. Pass Node-side values as arguments if the predicate needs them.

What does waitForSelector() return for a hidden wait?

It can return null when the selector is absent; when an element is found, it returns an ElementHandle.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Shenzhen desk3 min
    HONOR Expands Beyond Smartphones With Humanoid Robot RevealHONOR said it unveiled its first humanoid robot at MWC 2026 and named shopping assistance, workplace inspections, and supportive companionship as intended uses. Later Robotics D1 claims and a reported…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.