Hero Background

Power Your Software Testing with AI Agents and Cloud

The Native AI-Agentic Cloud Platform to Supercharge Quality Engineering. Test Intelligently and Ship Faster.

Selenium TutorialAutomation

Selenium Wait: Implicit, Explicit & Fluent Wait Commands

Selenium waits explained with Java examples: implicit, explicit and fluent waits, the Duration syntax Selenium 4 requires, and why you must not mix them.

Last Updated on:

Getting a Selenium suite to pass reliably comes down to how it handles waiting. Wait commands keep the script in step with the browser, so each step runs against an element that has finished loading instead of a half-rendered DOM.

This article will dive into Selenium waits and explain how testers use Selenium’s wait feature. We will cover all the Selenium waits: Implicit Waits, Explicit Waits, and Fluent Waits. We also break down the differences between implicit and explicit waits and explain when using each type of wait is best. If you are preparing for an interview you can learn more through Selenium interview questions.

Overview

Selenium waits synchronize test scripts with web elements loading at different speeds, using implicit waits for global, consistent load times and explicit waits for precise, condition-based synchronization of dynamic elements. These mechanisms prevent race conditions and improve test stability across varying page load times.

Why Do We Need Selenium Waits?

  • Preventing race conditions: Selenium waits ensure web elements are fully loaded before interaction, preventing errors where the script executes before the browser reaches the correct state.
  • Improving test stability: These mechanisms handle dynamic web pages and prevent test failures caused by timing issues or incomplete element loading.
  • Adapting to load times: Selenium waits dynamically adjust scripts to varying page loading speeds, making automated test execution more robust and reliable.

Can We Use Thread.sleep()?

  • Thread.sleep() limitations: This Java construct introduces static, fixed delays that make test scripts inefficient by waiting for the specified duration regardless of when the element actually loads.
  • Maintenance challenges: Using Thread.sleep() requires adding static delays at multiple points in the code, making test scripts difficult to maintain over time.

What Are the Types of Selenium Waits?

  • Implicit Wait: This global wait applies to all elements in a script, setting a maximum time for elements to appear in the DOM before throwing a TimeoutException.
  • Explicit Wait: This granular approach uses the WebDriverWait class to wait for specific conditions, such as element visibility or clickability, on individual dynamic elements.
  • Fluent Wait: This highly flexible wait uses the FluentWait class to define custom polling frequencies and specify which exceptions to ignore during the wait period.

What are the Common Mistakes to Avoid with Selenium Waits?

  • Over-relying on Implicit Waits: Relying solely on implicit waits can cause synchronization issues, whereas explicit or fluent waits provide more precise control.
  • Setting improper durations: Configuring wait times that are too short or too long leads to inconsistent and unreliable test results during execution.
  • Mixing wait strategies: Combining implicit and explicit wait types in the same script can cause conflicts and should be avoided to maintain consistency.

Why Do We Need Selenium Waits?

The primary challenge in test automation is ensuring the application is appropriately configured to execute a specific Selenium command as intended. One of the most common issues with test automation is race conditions. In a race condition, either the browser reaches the right state first (which results in the desired functionality), or the Selenium code gets executed first (which leads to unintended results). This race condition is one of the main reasons test results are unreliable.

The reason for such race conditions depends on many aspects, like network speed, content size, and the frontend technology/framework used. For Instance, Javascript frameworks like React or Angular take some time to load the different objects on the web page due to the dynamic update to the Document Object Model (also known as DOM).

Without an appropriate wait mechanism, automation tests tend to produce consistent results. The lack of stable and reliable test execution increases developer frustration and time spent debugging, ultimately reducing their productivity. To solve this problem, Selenium Waits comes to the rescue.

Can We Use Thread.sleep()?

Thread.sleep() is a Java construct that stops the program’s execution for a specified period. By using this, we can achieve the wait required to have reliable automation test scripts, but it comes with some challenges that discourage its use as follows:

  • Make Test Scripts Inefficient: Invocation of Thread.sleep() method waits for the specified period irrespective of any situation. This static behavior leads to unnecessary delays in executing the test scripts. Regardless of the load time of the elements while testing, the script will wait for a static duration and increase the test execution time.
  • Requires Explicit addition after every Selenium Command: While adding waits in the test scripts using Thread.sleep(), it requires adding it all the places, even though there is a requirement of a constant wait before accessing any element of the web page. This makes the test scripts difficult to maintain with time.
  • Sleep Duration Calculation: Determining the correct values for the sleep duration would become an essential and challenging task for every Selenium command.

Given these challenges, there are better solutions than using Thread.sleep(). Now, let’s look at Selenium waits, their different types, and how they address specific timing challenges in web automation.

Automate web and mobile tests with KaneAI by TestMu AI

What are Selenium Waits?

Selenium Waits is a test automation concept defined as three commands: Implicit Waits, Explicit Waits, and Fluent Waits, that facilitate synchronization between script actions and dynamic web elements.

These waits introduce pauses during test execution, allowing the script to wait until specific conditions are met. Rather than a mere pause, Selenium waits are intelligent as they adapt to the varying loading times of web pages. This ensures that automated tests remain robust and unaffected by potential element visibility or availability delays. As a result of Selenium waits, automation scripts in dynamic web environments are more reliable and stable.

Types of Selenium Wait Commands

Selenium provides three primary types of wait commands to handle different timing scenarios and enhance the reliability of the automated tests as follows:

  • Implicit Wait: Implicit Wait in Selenium is a global wait that applies to all elements in the script. It sets a maximum wait time for any element to become available before interaction. If the element appears within the specified time, the script continues; otherwise, it raises a TimeoutException.
  • Explicit Wait: Explicit Wait in Selenium is a more granular approach that allows you to wait for a specific condition or element. Explicit waits are applied to individual elements and provide better control and precision. It often uses the WebDriverWait class and expected conditions to define custom waiting criteria. Explicit waits are useful for efficiently handling dynamic web elements with different load times.
  • Fluent Wait: Fluent Wait in Selenium allows one to wait for a specific condition to be met with a custom frequency of checking the condition. Fluent waits are particularly useful when dealing with elements that may take varying times to load or change state. This wait is created using the FluentWait class and configured with options like timeout, polling frequency, and exceptions to ignore.

Watch the video to learn about different Selenium wait methods.

Youtube thumbnail

Implicit Wait In Selenium

In Selenium, an implicit wait is a mechanism instructing the WebDriver to wait for a certain period before throwing an exception. It is applied globally to the entire script, and its primary purpose is to wait for elements to be present in the DOM (Document Object Model) before performing actions on them.

When an implicit wait is set, the WebDriver will repeatedly poll the DOM for a specified duration until the element is found or the timeout period expires. If the element is found within the specified time, the WebDriver proceeds with the next step in the script. An exception is thrown if the element is not found during the implicit wait period.

For a complete breakdown of all wait strategies and how to choose between them, this guide to Selenium wait for page to load covers implicit, explicit, and fluent waits alongside page load strategies and AJAX-specific patterns.

By default, the value for implicit wait is set to zero, which means that if the element is not found, it will immediately return an error. To enable the Implicit Wait In Java, the following syntax is used on the web driver object.

import java.time.Duration;

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

Set the implicit wait once, immediately after initializing the WebDriver. It then applies to every element lookup for the rest of that driver session.

Older tutorials pass a time unit instead, as in implicitlyWait(10, TimeUnit.SECONDS). Selenium 4 removed that overload along with the other TimeUnit-based timeout methods, so the Duration form above is the only one that compiles against current releases. Add java.time.Duration to your imports.

One rule travels with the implicit wait. Per the Selenium documentation on waiting strategies: “Do not mix implicit and explicit waits. Doing so can cause unpredictable wait times. For example, setting an implicit wait of 10 seconds and an explicit wait of 15 seconds could cause a timeout to occur after 20 seconds.”

So treat it as a choice rather than a layer. If any part of your suite uses WebDriverWait or FluentWait, leave the implicit wait at its default of zero.

Youtube thumbnail

Explicit Wait In Selenium

Explicit wait in Selenium is a technique where the WebDriver is directed to wait for a certain condition to be met before proceeding with the execution of the next steps in the script. Unlike implicit wait, which is applied globally and waits a specified amount of time for elements to appear, explicit wait focuses on specific conditions for individual elements.

With explicit wait, wait for certain conditions such as an element’s presence, an element’s visibility, or a specific attribute can be configured for an element to be in a particular state before proceeding further. The explicit wait command is implemented using the Selenium WebDriverWait class in Java.

Below is the code snippet to understand how Explicit Wait can be configured and used.

The older new WebDriverWait(driver, 10) constructor, which took a plain number of seconds, was removed in Selenium 4. Every current constructor takes a Duration, and a second Duration can be passed to change the polling interval from its 500 millisecond default.

This snippet assumes no implicit wait is in play. If one is set, its global timeout stacks on top of this condition and the wait you actually get is neither 10 seconds nor the implicit value.

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("exampleId")));

Types of Expected Conditions

Explicit waits provide a way to wait for certain conditions to be met before executing the test script or raising exceptions for not being able to meet that condition. This is done with the help of Selenium’s ExpectedConditions class. Multiple conditions can be used for waits as follows:

  • Element Visibility: The visibilityOfElementLocated() condition ensures that an element is present in the DOM and visible on the page.
  • Element Clickability: The elementToBeClickable() condition is crucial for scenarios where an element needs interaction, such as clicking a button.
  • Text to Be Present In Element: The textToBePresentInElementLocated() condition ensures that the text is present in a specified element.
  • Presence of Elements: The presenceOfElementLocated() condition waits for at least one element to be present in the DOM.
  • The invisibility of Elements: The invisibilityOfElementLocated() condition waits for the specified element to be invisible.
  • Frame to Be Available and Switch To It: The frameToBeAvailableAndSwitchToIt() condition waits for the specified frame to be available and switches to it.
  • Alert to Be Present: The alertIsPresent() condition waits for an alert to be present and switches to it.
  • Element Selection State: The elementSelectionStateToBe() condition waits for an element to be in a particular state, either selected or unselected.
  • Staleness of Element: The stalenessOf() condition waits for an element to become stale, indicating that it is no longer attached to the DOM.
  • Custom Conditions with ExpectedConditions: The attributeToBe() condition waits for the definition of custom conditions. For instance, waiting for an element to have a specific attribute value.

You can explore the official Selenium Java documentation of the ExpectedConditions class to learn more.

Fluent Wait In Selenium

In Selenium, Fluent wait provides a more flexible way of waiting for certain conditions to be met before proceeding with the execution of the script. It implements the Wait interface and allows you to define the polling frequency and exceptions to ignore during the waiting period.

The fluent wait command is implemented using the Selenium FluentWait class in Java. The key feature of FluentWait is its “fluent” or chainable syntax, where you can apply different conditions and configurations in a chain.

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

   WebElement webElement =
       fluentWait.until(ExpectedConditions.presenceOfElementLocated(By.id("exampleId")));

As shown here in this code snippet, while instantiating the object for the Wait, we can mention the wait duration, polling duration, and the exception that this wait can ignore. Post instantiation of fluent wait, it can be used while accessing a web element by passing in a Function in the until method of wait.

Comparing Selenium Waits: Explicit, Implicit, and Fluent Waits

Picking the right waiting strategy in Selenium matters for smooth automation. Let’s compare Implicit, Explicit, and Fluent Waits to make it understandable.

CharacteristicImplicit WaitExplicit WaitFluent Wait
ScopeAffects all elements across the website universally.Can be applied individually to specific elements.Allows for personalized waiting strategies tailored to specific elements.
Complex Conditions SupportedBest suited for basic checks on whether an element is present or not.Supports a variety of conditions, like visibility or clickability, through explicit Conditions.Offers a high level of flexibility by accommodating user-defined specific conditions.
ConfigurationSet globally once for a consistent application throughout the entire website.Configurable independently for different elements, providing nuanced control.Resembles Explicit Wait but introduces additional configurations for heightened precision.
Use caseWell-suited for straightforward scenarios with consistent loading times.Ideal for tackling complex situations, especially when the loading behavior is unpredictable.Effective in dynamic scenarios marked by changes and variable loading times.
Wait Time ConfigurationGlobally set, ensuring a uniform waiting time across the entire site.Can be configured individually for specific elements or scenarios, allowing for granular control.Customizable on a per-element basis, enabling tailored waiting times.
Polling Interval ConfigOperates with a fixed default interval of 500ms between checks.Permits users to set the frequency of condition checks, defaulting to 500ms intervals.Adheres to the same polling interval configuration as Explicit Wait.
Ignoring ExceptionsLacks the ability to selectively ignore exceptions.Allows for selective suppression of specific errors during the waiting period.Aligns with Explicit Wait in terms of exception handling.
Combining With Other WaitsShould not be combined with Explicit or Fluent Waits. The global timeout stacks on top of the condition-based one.Safe alongside Fluent Wait, as long as the implicit wait stays at its default of zero.Safe alongside Explicit Wait, on the same condition that no implicit wait is set.
FlexibilityRelatively straightforward with limited customization options.Offers enhanced adaptability, accommodating various waiting scenarios.Highly adaptable, particularly beneficial for specific and nuanced situations.
Readability and ExpressBasic in nature due to its global application, providing less detailed insights.Exhibits greater expressiveness, especially when employing diverse Conditions.Demonstrates high expressiveness with a fluent API, contributing to code clarity.
Note

Note: Automate your tests on a Selenium based cloud Grid of 3000+ real browsers and devices. Try TestMu AI Today!

Common Mistakes to Avoid While Using Selenium Waits

Exploring Selenium waits is essential, but avoiding common mistakes is equally important. Some pitfalls to avoid while using Selenium waits:

  • Excessive Reliance on Implicit Waits: An implicit wait only checks whether an element has reached the DOM, so it cannot tell you the element is visible or clickable yet. In dynamic scenarios, replace it with an Explicit or Fluent Wait rather than running both, and set the implicit wait back to zero when you do.
  • Inadequate Wait Times: Avoid script failures by setting reasonable wait times. Elements may take longer to load; patience in allocating wait durations enhances the robustness of your tests.
  • Overlooking ExpectedConditions: Leverage the power of ExpectedConditions with Explicit and Fluent Waits. Neglecting these conditions might result in less adaptable and robust scripts.
  • Ignoring StaleElementReferenceException: Handle StaleElementReferenceException with care, which raises when an element is no longer attached to the DOM but a reference to the element is still being used. Ignoring it can lead to failures when interacting with stale elements. Use Explicit Waits judiciously to address this issue.
  • Poor Exception Handling: Wisely manage exception handling in Fluent Waits. Neglecting it may overlook crucial errors, affecting script reliability. Ensure effective debugging with meticulous exception management.
  • Neglecting Dynamic Conditions: Adapt your waits to the dynamic nature of web pages. Neglecting this may result in brittle scripts prone to failure. Selenium waits shine in dynamic scenarios.
  • Forgetting to Reset Implicit Waits: After modifying the Implicit Wait globally, remember to reset it. Forgetting to do so can impact other parts of your script, and maintaining consistency is crucial.
  • Mixing Implicit With Explicit or Fluent Waits: Explicit and Fluent Waits sit together safely, since both are scoped to one condition at a time. An implicit wait is global, so pairing it with either makes the two timeouts stack and the real wait time becomes hard to predict. Pick one model per suite, and keep the implicit wait at zero whenever that model is Explicit or Fluent.
  • Writing Your Own Polling Loops: WebDriverWait already handles the polling, the timeout, and the exception filtering. A hand-rolled loop around Thread.sleep() ends up longer than the class it replaces and behaves worse on slow pages.

Conclusion

Pages do not finish loading on a schedule, which is why Selenium ships wait commands at all. Thread.sleep() pauses for a fixed interval whether the element arrives in 200 milliseconds or never arrives. Selenium waits poll for a condition and continue the moment it holds.

The three types divide by scope. Implicit Wait is global and confirms only that an element reached the DOM. Explicit Wait targets one condition on one element through WebDriverWait. Fluent Wait does the same while letting you set the polling interval and the exceptions to ignore.

The practical rule is to pick one of them. An implicit wait running alongside WebDriverWait or FluentWait makes the two timeouts stack, and the wait you get back is neither number you configured. Keep the implicit wait at zero, drive your web automation with explicit or fluent waits, and the timing stays predictable as the suite grows.

Author

...

Vijay Kaushik

Blogs: 4

  • Twitter
  • Linkedin

Vijay Kaushik is a community contributor with 4+ years of experience as a software engineer, focused on building secure, scalable, and high-performance systems. He is proficient in Java, Python, Go, and JavaScript, with hands-on experience in cloud-native technologies such as Kubernetes and Istio. Currently working on end-to-end product delivery, Vijay has contributed to large-scale systems handling millions of transactions, with a strong emphasis on reliability, monitoring, and SDLC-driven engineering practices.

Reviewer

...

Himanshu Sheth

Reviewer

  • Linkedin

Himanshu Sheth is the Director of Marketing (Technical Content) at TestMu AI, with over 8 years of hands-on experience in Selenium, Cypress, and other test automation frameworks. He has authored more than 130 technical blogs for TestMu AI, covering software testing, automation strategy, and CI/CD. At TestMu AI, he leads the technical content efforts across blogs, YouTube, and social media, while closely collaborating with contributors to enhance content quality and product feedback loops. He has done his graduation with a B.E. in Computer Engineering from Mumbai University. Before TestMu AI, Himanshu led engineering teams in embedded software domains at companies like Samsung Research, Motorola, and NXP Semiconductors. He is a core member of DZone and has been a speaker at several unconferences focused on technical writing and software quality.

Add to Google preferred sources

Summarise with AI

Copied to Clipboard!
...

3000+ Browsers. One Platform.

See exactly how your site performs everywhere.

Try it free
...

Write Tests in Plain English with KaneAI

Create, debug, and evolve tests using natural language.

Try for free

Selenium Waits FAQs

Did you find this page helpful?

More Related Blogs

TestMu AI forEnterprise

Get access to solutions built on Enterprise
grade security, privacy, & compliance

  • Advanced access controls
  • Advanced data retention rules
  • Advanced Local Testing
  • Premium Support options
  • Early access to beta features
  • Private Slack Channel
  • Unlimited Manual Accessibility DevTools Tests