Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 35 ยท Async, Waiting and Flakiness

Auto-Waiting in Playwright

Learn how Playwright waits for you: actionability checks, async and await, waitFor, waitForURL, waitForResponse, and why waitForTimeout is a last resort.

Web pages are never ready instantly. Buttons appear after a request finishes, menus slide in over a few hundred milliseconds, and a form stays disabled until validation is done. A test that clicks too early fails for a reason that has nothing to do with a bug. Older tools forced you to sprinkle sleep(2000) calls through every test. Playwright takes a different approach: every action waits automatically until the element is ready, and every web-first assertion retries until it passes.

In this lesson you will learn the checks Playwright runs before an action, how async and await fit in, the explicit waits you sometimes still need (waitFor, waitForURL, waitForResponse), and why waitForTimeout should almost never appear in your tests. Then you will build an actionability poller as a stand-in. If you have not seen a Playwright test yet, read Your First Playwright Test first.

Playwright needs Node.js and real browsers, so its code is shown read-only. The runnable parts are stand-ins: small programs on a virtual clock that reproduce the waiting logic. They are not Playwright's source code, and the retry timings are simplified.

Every Playwright call is async

In Playwright, each action returns a promise. You write await in front of it, and the test function is async:

TypeScript
// Playwright (read-only)
import { test, expect } from '@playwright/test';

test('adds a todo', async ({ page }) => {
  await page.goto('/todos');
  await page.getByPlaceholder('What needs to be done?').fill('Buy milk');
  await page.getByRole('button', { name: 'Add' }).click();
  await expect(page.getByText('Buy milk')).toBeVisible();
});

The await is not decoration. Without it the test moves on while the action is still running, and the test can finish (and pass!) before anything was checked. Forgetting await on click() or on an expect is the single most common Playwright bug. A linter rule (@typescript-eslint/no-floating-promises) catches it, and Playwright's own docs recommend it. Compare this to Cypress, where commands are queued and you never await them: see How Cypress Commands Really Work.

Actionability checks

Before it performs an action, Playwright runs a set of actionability checks on the element and keeps retrying them until they all pass or the timeout expires. The checks depend on the action:

Check Meaning Used by
Visible Has a non-empty bounding box and is not visibility: hidden click, fill, check, hover
Stable Has held the same position for two animation frames in a row click, check, hover
Receives events The element is the one at the click point; nothing covers it click, check, hover
Enabled Not a disabled form control click, fill, check
Editable Enabled and not read-only fill

So click() waits for the button to be visible, to stop moving, to be uncovered by a spinner overlay, and to be enabled. Only then does it click. fill() waits for an editable field. If the checks do not pass before the timeout, the action throws an error that lists which check kept failing, which tells you what was wrong with the page.

flowchart TD
  A["Action requested: click()"] --> B{"Attached and visible?"}
  B -->|no| R["Wait a little, retry"]
  B -->|yes| C{"Stable?"}
  C -->|no| R
  C -->|yes| D{"Receives events?"}
  D -->|no| R
  D -->|yes| E{"Enabled?"}
  E -->|no| R
  E -->|yes| F["Perform the click"]
  R --> B
  R -->|"timeout reached"| X["Throw TimeoutError"]

Playwright keeps looping through the checks; only when all of them pass does the action happen.

By default individual actions have no timeout of their own: they are limited by the test timeout (30 seconds). You can set actionTimeout in the config to fail faster. Web-first assertions such as expect(locator).toBeVisible() have their own 5-second timeout. Both defaults are configurable; see Configuration and Environments.

A poller on a virtual clock

The stand-in below models one button whose state depends on time: it is attached at 100 ms, visible at 300 ms, slides until 500 ms, is covered by a spinner overlay until 650 ms, and becomes enabled at 800 ms. The poller tries the checks in order, waits a growing delay between attempts (roughly like Playwright's retry back-off, which starts with very short waits and grows), and reports the first failing check each time. The clock is virtual, so the run takes no real time and the output is the same every run.

Node.js An actionability poller

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The log walks through the failing checks in order: not attached, not visible, still sliding ("stable" is false at 470 ms), and finally disabled. The click lands at 970 ms, the first poll after enabled turned true at 800 ms. The second run throws because the 400 ms timeout ran out while the button was still invisible. The real error message from Playwright is longer, but it follows the same idea: it names the last check that failed and how long it waited. Notice that the poller did not wait a fixed time. It acted at the first poll after the element was ready.

Explicit waits you still need

Auto-waiting covers actions on elements. A few situations need an explicit wait:

TypeScript
// Playwright (read-only)

// 1. Wait for an element state without acting on it
await page.getByRole('status').waitFor({ state: 'hidden' });  // spinner gone
await page.locator('.toast').waitFor({ state: 'attached' });

// 2. Wait for navigation to settle on a URL
await page.getByRole('button', { name: 'Log in' }).click();
await page.waitForURL('**/dashboard');

// 3. Wait for a specific network response
const responsePromise = page.waitForResponse(
  (r) => r.url().endsWith('/api/orders') && r.status() === 201
);
await page.getByRole('button', { name: 'Place order' }).click();
const response = await responsePromise;
expect(await response.json()).toMatchObject({ status: 'created' });

In the third example, notice the order: you create the promise before you trigger the request, then await it afterwards. If you started waiting after the click, a fast response could arrive before you were listening, and the test would hang until it timed out.

Often you do not need an explicit wait at all. A web-first assertion such as await expect(page).toHaveURL(/dashboard/) or await expect(page.getByText('Order placed')).toBeVisible() already retries for you, and it describes the outcome you care about more clearly than a wait does. Network waiting is explained further in Intercepting and Mocking Network Requests.

Avoid waitForTimeout

page.waitForTimeout(3000) pauses for exactly three seconds. It is a guess. If the app needs 1 second, you waste 2 seconds on every run. If it needs 4 seconds on a slow CI machine, the test fails. Playwright's own documentation marks it as a debugging tool and warns against it in production tests. The stand-in below compares the three styles on the same app that becomes ready after a time that varies per run. It also shows the second classic bug: a missing await.

Node.js Fixed sleep, polling and the missing await

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The table makes the cost visible: polling is never slower than needed and never too early, while the fixed sleep wastes time in the fast runs and fails in the slowest run (needing 3400 ms, it passes the check too soon). The last two lines show why forgetting await reorders events: without it, "checked" comes first.

Practical rules

  • Always await actions, assertions and waitFor calls. Turn on the no-floating-promises lint rule.
  • Prefer a web-first assertion (await expect(locator).toBeVisible()) over reading a value and asserting on it yourself. expect(await locator.isVisible()).toBe(true) reads once and does not retry.
  • Use waitFor, waitForURL and waitForResponse when the thing you wait for is not an element you are about to act on.
  • Start waitForResponse before the action that triggers the request.
  • Treat waitForTimeout as a debugging aid only.
  • If an action times out, read which check failed. Usually the page really is in the state the message says: covered by an overlay, disabled, or hidden.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which is NOT one of the checks Playwright runs before clicking a button?

    Playwright checks visibility, stability, that the element receives events at the click point, and that it is enabled. A test id is a way to find an element, not an actionability check.
  2. 2. What happens if you forget the await in front of page.getByRole('button').click()?

    The click returns a promise. Without await the test function does not wait for it, so later lines can run too early or the test can end before the click completes.
  3. 3. When using page.waitForResponse() around a click, when should you create the promise?

    If you start listening after the click, a fast response may already have arrived. Create the promise first, click, then await it.
  4. 4. Why is page.waitForTimeout(3000) a poor way to wait for the page?

    A fixed pause is a guess. Auto-waiting and web-first assertions act the moment the condition becomes true.
  5. 5. Which line retries until the text appears?

    Web-first assertions are the ones that take a locator and retry. Reading a boolean first checks only once.

Summary

  • Playwright actions are async; always await them.
  • Before an action Playwright retries actionability checks: visible, stable, receives events, enabled and (for fill) editable.
  • Actions are bounded by the test timeout; web-first assertions have their own 5-second default.
  • Use waitFor, waitForURL and waitForResponse for things that are not an action target, and start response waits before the trigger.
  • Avoid waitForTimeout; prefer waiting for a condition.
  • The stand-ins use a virtual clock to show the logic; real Playwright waits in real time with its own back-off.

Next: Finding and Fixing Flaky Tests