Waits: implicit, explicit, fluent
Instead of Thread.sleep, a test waits for a page state through an explicit WebDriverWait, which returns as soon as the condition is met. Implicit wait is a global element-search timeout; it is kept at 0 and not mixed with explicit waits, because the total time becomes unpredictable. FluentWait adds configuration of the polling interval and ignored exceptions. A click needs elementToBeClickable.
Selenium · Waits
Thread.sleep(5000) after every step, the suite takes an hour and is still flaky. Why?
In payment tests a Thread.sleep(5000) follows a click. Sometimes the server answers in a second and four seconds are wasted. At peak hours the answer takes eight seconds and the test fails because the page has not updated yet. Five seconds is not a system requirement but a guess, and a guess is wrong in both directions. The page changes asynchronously, so a test must wait for a state, not for time. The lesson covers three wait mechanisms of Selenium, what each one actually checks, and why they are not mixed.
How it works and why. Selenium does not know when a page is "ready": the driver returns control when loading has finished, and whatever JavaScript draws afterwards does not concern it. So a wait is a loop in the test code: check the condition, if not yet, pause a short interval and repeat until a timeout expires. Selenium has three mechanisms.
- Implicit wait: a global element lookup timeout for the whole session, 0 by default. It is set once (
driver.manage().timeouts().implicitlyWait(...)) and applies to everyfindElement: the driver repeats the search until the element appears in the DOM. It waits only for presence in the DOM, not for visibility or clickability. - Explicit wait (
WebDriverWait): waits for a specific condition by polling the page; if the condition is not met by the end of the timeout, it throwsTimeoutException. The usual polling interval in Java is 500 ms. By default it ignoresNoSuchElementExceptionbetween attempts. - FluentWait: the same, but with a configurable timeout, polling interval and list of exceptions to ignore.
WebDriverWaitis its specialisation.
Time instead of a state and a state instead of time
Thread.sleep(5000)
Always five seconds: wasted time on a fast answer, a failure on a slow one. The cause of failure is not visible.
WebDriverWait
Returns as soon as the condition holds. The timeout sets a limit, and TimeoutException says what exactly was not reached.
Example: from sleep to conditions. The starting code:
driver.findElement(By.id("pay")).click();
Thread.sleep(5000); // "to be sure it has loaded"
String text = driver.findElement(By.id("status")).getText();
Instead of a pause we state exactly what we wait for. Each wait answers a concrete question about the page state:
WebDriverWait wait =
new WebDriverWait(driver, Duration.ofSeconds(10));
// 1. wait for the spinner covering the button to go away
wait.until(ExpectedConditions.invisibilityOfElementLocated(
By.cssSelector(".spinner")));
// 2. wait until the button is visible and enabled
wait.until(ExpectedConditions.elementToBeClickable(By.id("pay")))
.click();
// 3. wait for the final state we need
wait.until(ExpectedConditions.textToBe(
By.id("status"), "Paid"));
elementToBeClickable checks that the element is visible and enabled, but not that nothing else covers it (a spinner or a modal): that is a separate condition, so we first wait for the overlay to vanish. The last condition waits not for an element to appear but for the right content, since the status element may have been on the page from the start with old text. A condition can also be a lambda: it returns a value or null/false while not ready.
// a custom condition: the lambda returns a value or null/false
String total = wait.until(d -> {
String s = d.findElement(By.id("total")).getText();
return s.isBlank() ? null : s; // null = not ready yet
});
When fine tuning is needed (an interval, exceptions), use FluentWait:
Wait<WebDriver> fluent = new FluentWait<>(driver)
.withTimeout(Duration.ofSeconds(15))
.pollingEvery(Duration.ofMillis(300))
.ignoring(NoSuchElementException.class,
StaleElementReferenceException.class);
WebElement row = fluent.until(d -> d.findElement(By.id("row-7")));
Limits and alternatives. The Selenium documentation directly advises not to mix implicit and explicit waits: the total time becomes unpredictable. The documentation's example: an implicit wait of 10 seconds and an explicit one of 15 can give a timeout of about 20 seconds. The reason is that every findElement inside a condition itself waits the implicit time. So implicit stays 0 and waiting is explicit where needed.
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
// ... and somewhere later:
new WebDriverWait(driver, Duration.ofSeconds(15))
.until(ExpectedConditions.invisibilityOfElementLocated(By.id("x")));
// the waiting time is unpredictable, up to ~20 s
Separate from element waits there are the page load timeout (pageLoad, 300 seconds by default) and the asynchronous script timeout (script, 30 seconds by default). They are set when pages really are heavy:
driver.manage().timeouts()
.pageLoadTimeout(Duration.ofSeconds(30))
.scriptTimeout(Duration.ofSeconds(10));
In Playwright waiting is built into every action and assertion, so loops are rarely written there; in Selenium it is the test's responsibility, and it is convenient to hide it inside Page Object methods (the lesson “Page Object Model: what it is and the rules”). For flakiness that waits do not cure, see the lesson “Flaky tests: causes, diagnosis, artifacts and Allure”.
Common mistakes.
Thread.sleep"for reliability": tests are slow and still flaky.- Waiting for
presenceOfElementLocatedbefore a click: the element is in the DOM but hidden or covered, which ends inElementNotInteractableExceptionorElementClickInterceptedException. A click needselementToBeClickable. - A large implicit wait "just in case": an absence check (
findElements) now always waits the whole timeout. - Catching
TimeoutExceptionand carrying on: the wait error is hidden and the real cause is lost.
Check yourself
After adding implicitlyWait(10), the "spinner is gone" check through findElements(...).isEmpty() takes ten seconds when there is no spinner. Why?
Answer
The implicit wait applies to every lookup: when the element is absent, the driver repeats the search until the timeout ends before returning an empty list. So implicit stays 0 and an explicit condition such as invisibilityOfElementLocated is used for disappearance.
A test waits for elementToBeClickable(By.id("pay")) but the click still throws ElementClickInterceptedException. What happens and what should be added?
Answer
The condition checks visibility and enabled state, but between the check and the click a spinner or modal that appeared later may cover the button. Add a wait for the overlay to vanish (invisibilityOfElementLocated) before the click and find out what shows it.
Thread.sleep: I use the explicit WebDriverWait with ExpectedConditions, which waits for the needed state and returns as soon as it holds. Middle/Senior: I keep implicit at 0 and do not mix it with explicit, since time becomes unpredictable. I phrase a condition about a state (an overlay gone, a text, a URL), not about an element appearing. I use FluentWait when specific exceptions must be ignored or the interval changed, and I hide waits in the Page Object.