App & Browser Testing Made Easy

Give your users a seamless experience by testing on 3000+ real devices and browsers. Don't compromise with emulators and simulators

Home Guide Selenium Wait Commands: Implicit, Explicit, and Fluent Wait

Selenium Wait Commands: Implicit, Explicit, and Fluent Wait

By Shreya Bose, Community Contributor -

If you want to become an expert at using Selenium WebDriver, one of the most important skills to master is the use of the Wait commands in Selenium. They are essential for executing test scripts and help identify and resolve issues related to time lag in web elements.

This article will offer a detailed description of how developers and testers can use the Wait function in Selenium. It will also break down different types of Waits in Selenium, i.e. Implicit Wait, Explicit Wait, and Fluent Wait. It also highlights Implicit vs Explicit wait in order to provide clarity on when to use which function upon understanding the difference between implicit and explicit wait.

What are Wait commands in Selenium?

The wait commands are essential when it comes to executing Selenium tests. They help to observe and troubleshoot issues that may occur due to variation in time lag.

While running Selenium tests, it is common for testers to get the message “Element Not Visible Exception“. This appears when a particular web element with which WebDriver has to interact, is delayed in its loading. To prevent this Exception, Selenium Wait Commands must be used.

In automation testing, Selenium Webdriver wait commands direct test execution to pause for a certain length of time before moving onto the next step. This enables WebDriver to check if one or more web elements are present/visible/enriched/clickable, etc.

Wait commands in Selenium

Why do users need Selenium Webdriver Wait commands?

When a web page loads on a browser, various web elements (buttons, links, images) that someone wants to interact with may load at various intervals.

In automated Selenium testing, this causes some trouble when identifying certain elements. If an element is not located, then the “ElementNotVisibleException” appears. Selenium Wait commands help resolve this issue.

Read more about the Common Exceptions in Selenium.

Selenium WebDriver provides three commands to implement waits in tests.

  1. Implicit Wait
  2. Explicit Wait
  3. Fluent Wait

Implicit Wait in Selenium

Implicit Wait directs the Selenium WebDriver to wait for a certain measure of time before throwing an exception. Once this time is set, WebDriver will wait for the element before the exception occurs.

Once the command is run, Implicit Wait remains for the entire duration for which the browser is open. It’s default setting is 0, and the specific wait time needs to be set by the following protocol.

To add implicit waits in test scripts, import the following package.

import java.util.concurrent.TimeUnit;

Implicit Wait Syntax

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

Add the above code into the test script. It sets an implicit wait after the instantiation of WebDriver instance variable.

Example of Implicit Wait Command

Package waitExample;

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class WaitTest {

private WebDriver driver;
private String baseUrl;
private WebElement element;

@BeforeMethod
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = "http://www.google.com";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}

@Test
public void testUntitled() throws Exception {
driver.get(baseUrl);
element = driver.findElement(By.id("lst-ib"));
element.sendKeys("Selenium WebDriver Interview questions");
element.sendKeys(Keys.RETURN);
List<WebElement> list = driver.findElements(By.className("_Rm"));
System.out.println(list.size());

}

@AfterMethod
public void tearDown() throws Exception {
driver.quit();
}
}

However, implicit wait increases test script execution time. It makes each command wait for the defined time before resuming test execution. If the application responds normally, the implicit wait can slow down the execution of test scripts. Pro tip: If you are worried about slowing down your selenium test scripts, check out these 6 things to avoid.

Here is a Comprehensive Guide to Run your Selenium Test using BrowserStack Automate

Selenium Wait Commands: Implicit, Explicit, and Fluent Wait

Please find the Github repo here for the example cited in the video.

Try Wait Commands in Selenium for Free

Explicit Wait in Selenium

By using the Explicit Wait command, the WebDriver is directed to wait until a certain condition occurs before proceeding with executing the code.

Setting Explicit Wait is important in cases where there are certain elements that naturally take more time to load. If one sets an implicit wait command, then the browser will wait for the same time frame before loading every web element. This causes an unnecessary delay in executing the test script.

Explicit wait is more intelligent, but can only be applied for specified elements. However, it is an improvement on implicit wait since it allows the program to pause for dynamically loaded Ajax elements.

In order to declare explicit wait, one has to use ExpectedConditions. The following Expected Conditions can be used in Explicit Wait.

  1. alertIsPresent()
  2. elementSelectionStateToBe()
  3. elementToBeClickable()
  4. elementToBeSelected()
  5. frameToBeAvaliableAndSwitchToIt()
  6. invisibilityOfTheElementLocated()
  7. invisibilityOfElementWithText()
  8. presenceOfAllElementsLocatedBy()
  9. presenceOfElementLocated()
  10. textToBePresentInElement()
  11. textToBePresentInElementLocated()
  12. textToBePresentInElementValue()
  13. titleIs()
  14. titleContains()
  15. visibilityOf()
  16. visibilityOfAllElements()
  17. visibilityOfAllElementsLocatedBy()
  18. visibilityOfElementLocated()

To use Explicit Wait in test scripts, import the following packages into the script.

import org.openqa.selenium.support.ui.ExpectedConditions
import org.openqa.selenium.support.ui.WebDriverWait

Then, Initialize A Wait Object using WebDriverWait Class.

Explicit Wait Syntax

WebDriverWait wait = new WebDriverWait(driver,30);

Here, the reference variable is named <wait> for the <WebDriverWait> class. It is instantiated using the WebDriver instance. The maximum wait time must be set for the execution to layoff. Note that the wait time is measured in seconds.

Example of Explicit Wait Command

In the following example, the test script is for logging into “gmail.com” with a username and password. After a successful login, the code waits for the “compose” button to be available on the home page. Here, you have to wait until the element is visible (Compose Button in this case) using the explicit wait command. Finally, it clicks on the button.

package waitExample;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class ExpectedConditionExample {
// created reference variable for WebDriver
WebDriver driver;

@BeforeMethod
public void setup() throws InterruptedException {

// initializing driver variable using FirefoxDriver
driver=new FirefoxDriver();
// launching gmail.com on the browser
driver.get("https://gmail.com");
// maximized the browser window
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}

@Test
public void test() throws InterruptedException {
// saving the GUI element reference into a "element" variable of WebElement type
WebElement element = driver.findElement(By.id("Email"));
// entering username
element.sendKeys("dummy@gmail.com");
element.sendKeys(Keys.RETURN);
// entering password
driver.findElement(By.id("Passwd")).sendKeys("password");
// clicking signin button
driver.findElement(By.id("signIn")).click();
// explicit wait - to wait for the compose button to be click-able
WebDriverWait wait = new WebDriverWait(driver,30);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[contains(text(),'COMPOSE')]")));
// click on the compose button as soon as the "compose" button is visible
driver.findElement(By.xpath("//div[contains(text(),'COMPOSE')]")).click();
}

@AfterMethod
public void teardown() {
// closes all the browser windows opened by web driver
driver.quit();
}

}

The above code instructs Selenium WebDriver to wait for 30 seconds before throwing a TimeoutException. If it finds the element before 30 seconds, then it will return immediately. After that, it will click on the “Compose” button. In this case, the program will not wait for the entire 30 seconds, thus saving time and executing the script faster.

Fluent Wait in Selenium

Fluent Wait in Selenium marks the maximum amount of time for Selenium WebDriver to wait for a certain condition (web element) becomes visible. It also defines how frequently WebDriver will check if the condition appears before throwing the “ElementNotVisibleException”.

To put it simply, Fluent Wait looks for a web element repeatedly at regular intervals until timeout happens or until the object is found.

Fluent Wait commands are most useful when interacting with web elements that can take longer durations to load. This is something that often occurs in Ajax applications.

While using Fluent Wait, it is possible to set a default polling period as needed. The user can configure the wait to ignore any exceptions during the polling period.

Fluent waits are also sometimes called smart waits because they don’t wait out the entire duration defined in the code. Instead, the test continues to execute as soon as the element is detected – as soon as the condition specified in .until(YourCondition) method becomes true.

Fluent Wait Syntax

Wait wait = new FluentWait(WebDriver reference)
.withTimeout(timeout, SECONDS)
.pollingEvery(timeout, SECONDS)
.ignoring(Exception.class);

WebElement foo=wait.until(new Function<WebDriver, WebElement>() {
public WebElement applyy(WebDriver driver) {
return driver.findElement(By.id("foo"));
}
});

Example of Fluent Wait Command

//Declare and initialise a fluent wait
FluentWait wait = new FluentWait(driver);
//Specify the timout of the wait
wait.withTimeout(5000, TimeUnit.MILLISECONDS);
//Sepcify polling time
wait.pollingEvery(250, TimeUnit.MILLISECONDS);
//Specify what exceptions to ignore
wait.ignoring(NoSuchElementException.class)

//This is how we specify the condition to wait on.
//This is what we will explore more in this chapter
wait.until(ExpectedConditions.alertIsPresent());

This command operates with two primary parameters: timeout value and polling frequency. The above code defines the time out value as 5 seconds and polling frequency as 0.25 seconds. It directs WebDriver to wait for no more than 5 seconds to verify a specific condition. If the condition occurs during those 5 seconds, it will execute the next step in the test script. If not, it will return “ElementNotVisibleException”.

Run Selenium Tests on Real Devices

A few other associated commands are:

  • PageLoadTimeout Command

This command establishes the time WebDriver must wait for a page to completely load before triggering an error. In case the timeout set is negative, the page load time can be indefinite.

Syntax:

driver.manage().timeouts().pageLoadTimeout(100, SECONDS);
  • SetScriptTimeout Command

This command establishes the time WebDriver will wait for an asynchronous script to finish executing before triggering an error. Like the previous command, the script will run indefinitely if the timeout is set to a negative value.

Syntax:

driver.manage().timeouts().setScriptTimeout(100,SECONDS);
  • Sleep Command

Thread Sleep command is rarely used because it is quite ineffective. It causes WebDriver to wait for a specific time (and does not let it run faster even if the specified condition is met). In fact, Selenium wait commands are considered the smarter, more effective alternative to the Sleep command.

Syntax:

thread.sleep(1000);

Difference between Implicit and Explicit Wait Commands in Selenium

The major difference between implicit and explicit wait is that: Implicit wait is applicable to all the elements in the test script, Explicit wait applies to the specific element only.

Here is the detailed illustration of Implicit vs Explicit Wait in Selenium below to help you understand when to use which.

Implicit Wait in SeleniumExplicit Wait in Selenium
Applies to all elements in a test script. Applies only to specific elements as intended by the user. 
No need to specify “ExpectedConditions” on the element to be locatedMust always specify “ExpectedConditions” on the element to be located
Most effective when used in a test case in which the elements are located with the time frame specified in implicit waitMost effective when used when the elements are taking a long time to load. Also useful for verifying property of the element, such as visibilityOfElementLocated, elementToBeClickable, elementToBeSelected

Mastering the use of Selenium Wait commands is fundamentally necessary for testers to set up efficient test automation. Effective implementation of waits can greatly simplify processes such as automated selenium testing. It saves time and effort and helps to detect anomalies on web pages, thus ensuring that software testing becomes easier to initiate, execute and review.

Selenium Waits help detect and debug issues that may occur due to variations in time lag. However, for the results of these commands to be 100% accurate all the time, they must be run on real browsers and devices rather than emulators or simulators to take real user conditions into account while testing. Using BrowserStack’s real device cloud, you get access to 3000+ real browser device combinations, which makes testing comprehensive.

Test on BrowserStack Cloud Selenium Grid to run Selenium tests on multiple device-browser combinations simultaneously using Parallel testing.

Run Selenium Tests on Real Devices

Tags
Automation Testing Selenium Selenium Webdriver

Featured Articles

How to get Selenium to wait for a page to load

Understanding ExpectedConditions in Selenium (with Types and Examples)

Curated for all your Testing Needs

Actionable Insights, Tips, & Tutorials delivered in your Inbox
By subscribing , you agree to our Privacy Policy.
thank you illustration

Thank you for Subscribing!

Expect a curated list of guides shortly.