Saturday, December 5, 2026

Implicit and Explicit Wait in Selenium Java

Implicit and Explicit Wait in Selenium Java

In Selenium WebDriver, Implicit Wait and Explicit Wait are synchronization techniques used to handle dynamic web elements. They help Selenium wait until elements are available or meet specific conditions before performing actions.

Without waits, Selenium may execute commands faster than the web application can load elements, resulting in exceptions such as NoSuchElementException or ElementNotInteractableException.

Implicit and Explicit Wait in Selenium Java


1. What is Implicit Wait in Selenium?

Implicit Wait is a global wait applied to all elements in the WebDriver session. Selenium waits for a specified amount of time when trying to locate an element before throwing a NoSuchElementException.

If the element is found before the timeout, Selenium continues execution immediately.

Syntax

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

Example: Implicit Wait

import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class ImplicitWaitExample {

    public static void main(String[] args) {

        WebDriver driver = new ChromeDriver();

        // Apply implicit wait
        driver.manage().timeouts()
              .implicitlyWait(Duration.ofSeconds(10));

        driver.manage().window().maximize();

        driver.get("https://www.google.com");

        // Selenium waits up to 10 seconds
        driver.findElement(By.name("q")).sendKeys("Selenium Java");

        driver.quit();
    }
}

How Implicit Wait Works

Suppose the implicit wait is configured for 10 seconds.

Element loading time Selenium behavior
2 seconds Continues after 2 seconds
5 seconds Continues after 5 seconds
8 seconds Continues after 8 seconds
10 seconds Throws exception if not found

Important points:

  • Implicit wait is applied globally.
  • It applies to element location operations.
  • It does not wait for an element to become clickable or visible.
  • It remains active throughout the WebDriver session.
  • It is configured only once, generally after driver initialization.

2. What is Explicit Wait in Selenium?

Explicit Wait is a conditional wait used to wait for a particular condition before proceeding with the next operation.

Unlike implicit wait, explicit wait can be applied to individual elements or specific conditions.

Selenium provides the WebDriverWait class and ExpectedConditions class to implement explicit waits.

Syntax

WebDriverWait wait = new WebDriverWait(
    driver, Duration.ofSeconds(10)
);

wait.until(ExpectedConditions.visibilityOfElementLocated(
    By.id("username")
));

Example: Explicit Wait

import java.time.Duration;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class ExplicitWaitExample {

    public static void main(String[] args) {

        WebDriver driver = new ChromeDriver();

        driver.manage().window().maximize();

        driver.get("https://example.com");

        // Create explicit wait
        WebDriverWait wait = new WebDriverWait(
            driver, Duration.ofSeconds(10)
        );

        // Wait until element is visible
        WebElement element = wait.until(
            ExpectedConditions.visibilityOfElementLocated(
                By.id("username")
            )
        );

        element.sendKeys("admin");

        driver.quit();
    }
}

Important points:

  • Explicit wait is condition-based.
  • It can be applied to specific elements.
  • It waits until the expected condition becomes true.
  • It throws TimeoutException if the condition is not satisfied within the timeout.
  • It supports different conditions such as visibility, clickability, presence and alert availability.

3. Types of Expected Conditions in Selenium

Selenium provides several predefined expected conditions.

Expected Condition Description
visibilityOfElementLocated() Waits until an element is visible.
elementToBeClickable() Waits until an element is visible and enabled.
presenceOfElementLocated() Waits until an element is present in the DOM.
titleContains() Waits until the page title contains specified text.
titleIs() Waits until the page title matches the expected title.
alertIsPresent() Waits until an alert appears.
invisibilityOfElementLocated() Waits until an element becomes invisible or disappears.
textToBePresentInElement() Waits until an element contains specific text.
frameToBeAvailableAndSwitchToIt() Waits for a frame and switches to it.
urlContains() Waits until the URL contains specified text.
numberOfElementsToBe() Waits until the expected number of elements is present.
stalenessOf() Waits until an element is detached from the DOM.

Example: Wait Until Element Is Clickable

WebDriverWait wait = new WebDriverWait(
    driver, Duration.ofSeconds(10)
);

WebElement loginButton = wait.until(
    ExpectedConditions.elementToBeClickable(
        By.id("login")
    )
);

loginButton.click();

Example: Wait Until Element Is Visible

WebDriverWait wait = new WebDriverWait(
    driver, Duration.ofSeconds(10)
);

WebElement username = wait.until(
    ExpectedConditions.visibilityOfElementLocated(
        By.id("username")
    )
);

username.sendKeys("admin");

Example: Wait Until Alert Is Present

WebDriverWait wait = new WebDriverWait(
    driver, Duration.ofSeconds(10)
);

Alert alert = wait.until(
    ExpectedConditions.alertIsPresent()
);

System.out.println(alert.getText());

alert.accept();

4. What is Fluent Wait in Selenium?

Fluent Wait is another synchronization mechanism in Selenium that allows you to configure:

  • Maximum timeout.
  • Polling frequency.
  • Exceptions to ignore.
  • A custom condition to evaluate.

It repeatedly checks the condition at the specified polling interval until the condition is satisfied or the timeout expires.

Syntax

Wait<WebDriver> wait = new FluentWait<>(driver)
    .withTimeout(Duration.ofSeconds(30))
    .pollingEvery(Duration.ofSeconds(2))
    .ignoring(NoSuchElementException.class);

Example: Fluent Wait

import java.time.Duration;

import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.FluentWait;

public class FluentWaitExample {

    public static void main(String[] args) {

        WebDriver driver = new ChromeDriver();

        driver.manage().window().maximize();

        driver.get("https://example.com");

        FluentWait<WebDriver> wait = new FluentWait<>(driver)
            .withTimeout(Duration.ofSeconds(30))
            .pollingEvery(Duration.ofSeconds(2))
            .ignoring(NoSuchElementException.class);

        WebElement element = wait.until(
            d -> d.findElement(By.id("username"))
        );

        element.sendKeys("admin");

        driver.quit();
    }
}

Note: FluentWait is also the underlying configurable waiting mechanism used by WebDriverWait.

5. Difference Between Implicit Wait and Explicit Wait

Feature Implicit Wait Explicit Wait
Definition Global wait for element location Wait for a specific condition
Scope Entire WebDriver session Specific wait statement
Condition-based No Yes
WebDriver class WebDriver timeouts WebDriverWait
ExpectedConditions Not supported directly Supported
Custom polling Not configurable Configurable
Visibility check No Yes
Clickability check No Yes
Alert handling No Yes
Timeout exception NoSuchElementException TimeoutException
Flexibility Less flexible More flexible

6. Difference Between Explicit Wait and Fluent Wait

Feature Explicit Wait (WebDriverWait) Fluent Wait
Purpose Wait for a specific condition Wait with configurable polling and exception handling
Timeout Configurable Configurable
Polling interval Default polling interval Custom polling interval
Ignore exceptions Can be configured Can be configured
ExpectedConditions Supported Supported through until()
Custom conditions Supported Supported
Implementation Extends FluentWait Configurable wait implementation

7. What is Thread.sleep() in Selenium?

Thread.sleep() is a Java method used to pause program execution for a specified amount of time.

Unlike Selenium waits, it does not check whether an element is available or ready.

Example

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class ThreadSleepExample {

    public static void main(String[] args) throws InterruptedException {

        WebDriver driver = new ChromeDriver();

        driver.get("https://example.com");

        // Pause execution for 5 seconds
        Thread.sleep(5000);

        driver.findElement(By.id("username")).sendKeys("admin");

        driver.quit();
    }
}

Difference Between Thread.sleep() and Selenium Waits

Feature Thread.sleep() Implicit Wait Explicit Wait
Type Java method Selenium wait Selenium wait
Wait condition Fixed time Element location Specific condition
Checks condition No Yes Yes
Execution Always waits full duration Stops when element is found Stops when condition is met
Flexibility Low Low High
Recommended Avoid where possible Limited use Highly recommended

8. Can We Use Implicit Wait and Explicit Wait Together?

Technically, Selenium allows both implicit and explicit waits to be configured together. However, it is not recommended because combining them can lead to unpredictable and longer wait times.

For example:

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

WebDriverWait wait = new WebDriverWait(
    driver, Duration.ofSeconds(20)
);

wait.until(
    ExpectedConditions.visibilityOfElementLocated(
        By.id("username")
    )
);

Here, the implicit wait can affect the time taken by element location operations inside the explicit wait.

Best practice: Prefer explicit waits for synchronization and keep implicit wait at zero to avoid unexpected interactions.

9. Real-Time Example: Login Page Using Explicit Wait

import java.time.Duration;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class LoginTest {

    public static void main(String[] args) {

        WebDriver driver = new ChromeDriver();

        try {

            driver.manage().window().maximize();

            driver.get("https://example.com/login");

            WebDriverWait wait = new WebDriverWait(
                driver, Duration.ofSeconds(15)
            );

            // Wait for username field
            WebElement username = wait.until(
                ExpectedConditions.visibilityOfElementLocated(
                    By.id("username")
                )
            );

            username.sendKeys("admin");

            // Wait for password field
            WebElement password = wait.until(
                ExpectedConditions.visibilityOfElementLocated(
                    By.id("password")
                )
            );

            password.sendKeys("admin123");

            // Wait for login button
            WebElement loginButton = wait.until(
                ExpectedConditions.elementToBeClickable(
                    By.id("login")
                )
            );

            loginButton.click();

            // Wait for successful login message
            WebElement message = wait.until(
                ExpectedConditions.visibilityOfElementLocated(
                    By.id("successMessage")
                )
            );

            System.out.println(message.getText());

        } finally {
            driver.quit();
        }
    }
}

Note: example.com/login and the element IDs are illustrative. Replace them with the actual application URL and locators.

10. Best Practices for Waits in Selenium Automation

  1. Prefer explicit waits over Thread.sleep().
  2. Use WebDriverWait for dynamic web elements.
  3. Use elementToBeClickable() before clicking dynamic buttons.
  4. Use visibilityOfElementLocated() before entering text.
  5. Avoid mixing implicit and explicit waits.
  6. Keep timeout values reasonable.
  7. Use FluentWait when custom polling or exception handling is required.
  8. Create reusable wait methods in your Selenium automation framework.
  9. Always use meaningful timeout values based on application performance.
  10. Handle TimeoutException appropriately in your test framework.

Reusable Explicit Wait Utility

In a Selenium framework, you can create a reusable utility class.

import java.time.Duration;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class WaitUtils {

    private WebDriver driver;
    private WebDriverWait wait;

    public WaitUtils(WebDriver driver) {

        this.driver = driver;

        this.wait = new WebDriverWait(
            driver, Duration.ofSeconds(15)
        );
    }

    public WebElement waitForVisibility(By locator) {

        return wait.until(
            ExpectedConditions.visibilityOfElementLocated(locator)
        );
    }

    public WebElement waitForClickable(By locator) {

        return wait.until(
            ExpectedConditions.elementToBeClickable(locator)
        );
    }

    public boolean waitForInvisibility(By locator) {

        return wait.until(
            ExpectedConditions.invisibilityOfElementLocated(locator)
        );
    }
}

Usage

WaitUtils waitUtils = new WaitUtils(driver);

waitUtils.waitForVisibility(By.id("username"))
         .sendKeys("admin");

waitUtils.waitForClickable(By.id("login"))
         .click();

11. Selenium Waits Interview Questions and Answers

Q1. What is the difference between implicit and explicit wait?

Implicit wait is applied globally to element location operations, whereas explicit wait waits for a specific condition.

Q2. Which wait is better in Selenium?

Explicit wait is generally preferred because it supports condition-based synchronization and provides better control.

Q3. What happens if an element is not found within implicit wait?

Selenium throws NoSuchElementException.

Q4. What happens if an explicit wait condition is not satisfied?

Selenium throws TimeoutException.

Q5. Can we use multiple explicit waits in one test case?

Yes. You can create and use multiple explicit waits for different elements and conditions.

Q6. What is the default polling interval of WebDriverWait?

The default polling interval in Selenium 4's FluentWait implementation is 500 milliseconds.

Q7. Can explicit wait handle alerts?

Yes. Use ExpectedConditions.alertIsPresent().

Q8. Can implicit wait handle visibility conditions?

No. Implicit wait only affects finding elements, not their visibility or clickability.

Q9. What is FluentWait?

FluentWait provides configurable timeout, polling frequency and ignored exceptions.

Q10. Why should we avoid Thread.sleep()?

It always pauses execution for the specified duration, even if the element becomes available earlier.

12. Quick Revision

Implicit Wait

Global

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

Explicit Wait

Condition-based

WebDriverWait wait =
    new WebDriverWait(driver, Duration.ofSeconds(10));

wait.until(ExpectedConditions
    .elementToBeClickable(By.id("login")));

Fluent Wait

Custom polling

new FluentWait<>(driver)
    .withTimeout(Duration.ofSeconds(30))
    .pollingEvery(Duration.ofSeconds(2))
    .ignoring(NoSuchElementException.class);

Thread.sleep()

Fixed delay

Thread.sleep(5000);

Interview takeaway: In real-world Selenium automation frameworks, use Explicit Wait with WebDriverWait and ExpectedConditions for reliable synchronization. Avoid unnecessary hardcoded delays and mixing implicit and explicit waits.

No comments:

Post a Comment