Stable Selenium waits without Thread.sleep

Fixed sleeps are the most common cause of slow, flaky UI tests. Here's how to replace them with waits that are both faster and more reliable, in plain Selenium and in Serenity BDD.

By Joseph Ofoma · 5 October 2026 · 7 min read

Why Thread.sleep fails you twice

A web page doesn't update the moment you click. Requests go out, JavaScript runs and the DOM changes some milliseconds later. The quick fix is a sleep:

driver.findElement(By.id("save")).click();
Thread.sleep(3000); // wait for the confirmation
assertEquals("Saved", driver.findElement(By.id("status")).getText());

This fails you in two ways:

The fix is to wait for a condition, not for an amount of time: poll until the thing you need is true, and give up only after a generous timeout.

Implicit waits: avoid mixing them in

Selenium's implicit wait (driver.manage().timeouts().implicitlyWait(...)) makes every findElement retry until the element exists. It sounds convenient, but it only waits for presence, not for visibility or text. It also slows down every check that expects an element to be absent, and it interacts unpredictably with explicit waits. The Selenium documentation warns against mixing the two. Set the implicit wait to zero and use explicit waits instead.

Explicit waits with WebDriverWait

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
driver.findElement(By.id("save")).click();
WebElement status = wait.until(
        ExpectedConditions.textToBePresentInElementLocated(By.id("status"), "Saved"));

This returns as soon as the text appears and fails only after 10 seconds. ExpectedConditions covers the common cases: visibility, clickability, text, URL, title, alerts and invisibility.

FluentWait for anything else

When no built-in condition fits, FluentWait lets you poll any function and ignore exceptions that are expected while the page is changing:

new FluentWait<>(driver)
        .withTimeout(Duration.ofSeconds(10))
        .pollingEvery(Duration.ofMillis(250))
        .ignoring(StaleElementReferenceException.class)
        .until(d -> d.findElements(By.cssSelector(".cart-item")).size() == 1);

Ignoring StaleElementReferenceException matters. When a list re-renders, an element you just found can be replaced, and the next poll will simply find the new one.

Serenity BDD's smart waits

Serenity BDD builds waiting into its page objects. Elements found with $() or find() are WebElementFacades, which wait for the element before interacting with it:

public class ProfilePage extends PageObject {
    private static final String SAVE = "[data-test='save']";
    private static final String STATUS = "[data-test='status']";

    public void save() {
        $(SAVE).click();                      // waits until the button can be clicked
    }

    public String status() {
        return $(STATUS).waitUntilVisible().getText();
    }
}

The timeout is set once in serenity.conf rather than scattered through the code:

webdriver {
  timeouts.implicitlywait = 0
  wait.for.timeout = 10000
}

Retrying assertions: the missing piece

Waiting for an element isn't the same as waiting for the right state. A cart badge can be visible and still show the old count for a moment. If the assertion runs once, it fails intermittently.

The robust pattern is to retry the assertion itself until it passes or the timeout expires, then report the last real failure, so the error message still says what was wrong. This is how EffortlessATF's assertion steps work:

/** Retries an assertion until it passes or the wait timeout expires, then reports its last failure. */
private void eventually(Runnable assertion) {
    AssertionError[] lastFailure = new AssertionError[1];
    try {
        new FluentWait<>(driver())
                .withTimeout(waitTimeout())
                .pollingEvery(Duration.ofMillis(250))
                .ignoring(StaleElementReferenceException.class)
                .until(d -> {
                    try { assertion.run(); return true; }
                    catch (AssertionError e) { lastFailure[0] = e; return false; }
                });
    } catch (TimeoutException e) {
        if (lastFailure[0] != null) throw lastFailure[0];
        throw e;
    }
}

@Then("{element} should have the text {string}")
public void shouldHaveText(ElementRef element, String expected) {
    eventually(() -> assertThat(firstVisible(element).getText()).isEqualTo(expected));
}

Because every assertion step waits like this, the feature files contain no waits at all:

When I click "Remove from cart button" for "Sauce Labs Backpack"
Then "Cart badge" should have the text "1"

Rules of thumb

Get these patterns out of the box

EffortlessATF ships with smart waits and retrying assertions for every UI step, so your tests have no sleeps from day one.