Skip to content
CodeKruPro

Automation tool (Selenium) · Java

Waits

Implicit, explicit and fluent waits, and fixing timing problems.

Learn: Waits in Selenium Java: implicit, explicit and fluent8 minute read

A wait tells Selenium to pause until something is true, such as "the Save button is clickable". Modern pages load data in the background, animate and redraw parts of the screen, and Selenium does not wait for any of that by itself. A test that acts too early fails at random, which is called a flaky test. That is why interviewers ask about waits in nearly every round.

Why a fixed sleep is the wrong tool

Thread.sleep(5000) always costs five seconds, even when the page was ready after two, and it is still too short on a slow day. A wait for a condition checks again and again, returns as soon as the condition is true, and fails only after a timeout (the longest time you allow it to wait).

Timeline: a five-second sleep always waits five seconds; an explicit wait checks every half second and returns at two seconds when the element appears, or throws TimeoutException at ten seconds.
An explicit wait ends as soon as its condition is true.

Implicit wait

driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));

This is a driver setting. From then on, every findElement keeps retrying until the element exists or five seconds pass. Its default is 0. It only waits for presence in the DOM (the page's element tree). It cannot wait for an element to become visible, clickable or to disappear, and it makes every "is it absent?" check slow, because findElements waits the full time before returning an empty list.

Explicit wait

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

An explicit wait waits for one condition at one place in the test. WebDriverWait checks the condition every 500 ms (half a second), ignores NotFoundException (the parent of NoSuchElementException) between checks, and throws TimeoutException when time runs out. In Selenium 4 the constructor takes a java.time.Duration; old code with new WebDriverWait(driver, 10) does not compile.

Conditions you will use most, from ExpectedConditions (a Selenium class with ready-made conditions):

  • visibilityOfElementLocated and invisibilityOfElementLocated, for messages and spinners.
  • elementToBeClickable: visible and enabled.
  • presenceOfElementLocated: in the DOM, maybe hidden.
  • textToBePresentInElementLocated, numberOfElementsToBe, alertIsPresent, stalenessOf (waits until an old element reference is no longer valid; see Selenium exceptions and debugging).

Fluent wait and custom conditions

A fluent wait lets you choose the timeout, how often to check (the polling interval) and which exceptions to ignore. WebDriverWait is itself a FluentWait with ready-made defaults.

Wait<WebDriver> wait = new FluentWait<>(driver)
        .withTimeout(Duration.ofSeconds(30))
        .pollingEvery(Duration.ofMillis(500))
        .ignoring(NoSuchElementException.class)
        .withMessage("status never became Completed");

WebElement status = wait.until(d -> {
    WebElement el = d.findElement(By.id("status"));
    return el.getText().equals("Completed") ? el : null;
});

The lambda (a short inline function) runs on every check. Returning null or false means "keep waiting"; any other value ends the wait and is returned. In the code above, the lambda returns the element once its text is Completed, and null before that. Use custom conditions for what the built-in list lacks, such as a table reaching 50 rows.

Do not mix implicit and explicit waits

Selenium's documentation warns that mixing them makes wait times unpredictable. Inside an explicit wait, each lookup can also wait for the implicit timeout. Waiting for a spinner to disappear shows it best: once the spinner is removed from the page, the check that should confirm it first waits the full implicit time before it can report "not found". Most frameworks keep the implicit wait at 0 and use explicit waits only.

AJAX and the other timeouts

AJAX means the page loads data in the background after it opens. The page load finishing says nothing about that data, so wait for what the user would see: the spinner gone, the new row visible, the text changed. A new session also has a page load timeout of 300 seconds and a script timeout of 30 seconds, set with pageLoadTimeout(Duration) and scriptTimeout(Duration).

How to answer in an interview

Define the three waits in one line each, then say which you use: "I keep the implicit wait at 0 and put explicit waits in page object methods (a page object is a class that holds the locators and actions of one page), so every action waits for the right state." Give one example, such as waiting for a spinner to become invisible before clicking Save.

Common mistakes

  • Using Thread.sleep to "fix" a flaky test.
  • Waiting for presence when the test needs visibility or clickability.
  • Setting a large implicit wait and also using explicit waits.
  • Importing java.util.NoSuchElementException by mistake. Import org.openqa.selenium.NoSuchElementException by name.

Recap

Wait for states, not for time. The implicit wait covers presence only and its default is 0. WebDriverWait with ExpectedConditions covers most needs; FluentWait or a lambda covers the rest. Do not mix the two kinds.

15 questions0/15 solved

StatusQuestionDifficultyAsked in
Not startedWhich wait applies to every element lookup?EasyAsked in: Accenture, BrowserStack, Capgemini +4
Not startedWhy avoid fixed sleeps and mixing implicit with explicit waits?MediumAsked in: Accenture
Not startedWait until an element is visibleMediumAsked in: Accenture, BrowserStack, Capgemini +4
Not startedSet an implicit wait and read it backEasy-MediumAsked in: Accenture, BrowserStack, Capgemini +4
Not startedWait until a button is clickableMediumAsked in: Accenture, BrowserStack, Capgemini +4
Not startedWait until an element disappearsMediumAsked in: Infosys
Not startedWait for two elements that appear at different timesMediumAsked in: Infosys
Not startedWait for appearing content and check what is still hiddenMediumAsked in: Capgemini, Infosys, TCS +1
Pro+Implicit, explicit and fluent waits in JavaMediumAsked in: Accenture, BrowserStack, Capgemini +4
Pro+A FluentWait with a custom condition (Java)MediumAsked in: Infosys, TCS, Wipro
Pro+WebDriverWait defaults in Selenium JavaMediumAsked in: Accenture, BrowserStack, Capgemini +4
Pro+How do you handle AJAX or content that loads after the page?MediumAsked in: Infosys
Pro+The three driver timeouts and their defaults (Java)Medium-Hard
Pro+Page load strategies: normal, eager and noneMedium
Pro+Why does new WebDriverWait(driver, 10) not compile?Easy-MediumAsked in: Accenture, Infosys, Wipro
Not startedNot startedIn progressIn progressSolvedSolvedPro+Pro+

The first 2 questions of each topic are free. Pro+ opens every question.

Back to the plan