You are viewing our old blog site. For latest posts, please visit us at the new space. Follow our publication there to stay updated with tech articles, tutorials, events & more.

Difference between Implicit and Explicit Wait in Selenium

0.00 avg. rating (0% score) - 0 votes
What is a wait and why it is used in automation scripts?

Have you ever seen a traffic signal? What does the Red light in the Traffic signal indicate? The origin of wait comes from the traffic signal problem. As Red light in traffic signal asks the traffic to halt for some time, similarly wait is used to halt the execution of our automation script for a specified time. In other words wait asks our script to stop the execution for a specified time. Wait is mostly used by automation testers like us to debug our code or to avoid situations like Element not found Exception(s) by the webdriver. ‘Element not found’ situation arises because elements within the page may load at different time intervals.
Usually in Selenium there can be two types of waits:
  1. Implicit Wait
  2. Explicit Wait
types of wait
In this blog I’ll take you through both types of waits with example. So continuing with our topic lets go through each type of wait one by one.
Implicit Wait: Implicit as the word itself suggests is “suggested though not directly expressed”. So what I mean by this. An implicit wait is to tell WebDriver to poll the DOM for a certain amount of time when trying to find an element or elements if they are not immediately available. The default setting is 0. Once set, the implicit wait is set for the life of the WebDriver object instance.
– Reference: SeleniumHq.org site
Example to set Implicit Wait:
  1. Setting Implicit Wait in Seconds:
public String SetImplicitWaitInSeconds(int timeOut){
        driver.manage().timeouts().implicitlyWait(timeOut, TimeUnit.SECONDS);
        return “Timeout set to “+timeOut+” seconds.”;
}
  1. Setting Implicit Wait in MilliSeconds:
public String SetImplicitWaitInMilliSeconds(int timeOut){
        driver.manage().timeouts().implicitlyWait(timeOut, TimeUnit.MILLISECONDS);
        return “Timeout set to “+timeOut+” milli seconds.”;
}
The code above accepts two arguments ie Timeout duration and unit of duration. Unit of duration can be Seconds, Milliseconds For example if we have to wait for 20 seconds then we will use the first function with replacing timeout with 20.
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
Explicit Wait
In Selenium there can be 2 types of Explicit Wait:
  1. Using Thread.Sleep : This is not recommended to use generally. Using this method we clearly give webdriver the instruction to halt the execution of next line of code until the maximum time has elapsed
try{Thread.sleep(TimeInMillis);}
catch(Exception e){}
Here Time mentioned should be in miliseconds.
  1. Using Web Driver wait: This type of wait is used when we want webdriver to halt the execution until a condition is met or maximum time has elapsed. This wait is implied to specific object only. Major advantage of using Webdriver Wait is as soon as the condition is met the execution of the script will start even if maximum elapsed time is remaining. So for example if we have mention 10 seconds maximum elapsed time and our condition is met at 7 seconds then script will not wait for another 3 seconds to start execution. In this case, 3 seconds of the time is saved. This is a major advantage of using this type of explicit wait over thread.sleep().
To implement Web driver wait we use classes WebDriverWait and ExpectedConditions in our execution suite.
Expected Conditions:
Below I’ll mention few methods which are defined in the ExpectedConditions class:
  1. elementToBeClickable() : This is used check whether the visisble element is clickable or not .
Example: wait.until(ExpectedConditions.elementToBeClickable(By.xpath(Element)));
  1. visibilityOfElementLocated(): This checks whether the Element is visible or not.
Below is a simple example to illustrate this condition:
WebDriverWait wait = new WebDriverWait(driver, 10);
Wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(Element)));
  1. alertIsPresent()- The expected condition waits for an alert box to appear.
Example:
wait.until(ExpectedConditions.alertIsPresent()) !=null);
  1. titleIs() – The expected condition waits for a page with a specific title.
Example:
wait.until(ExpectedConditions.titleIs(“Naukri”));
Explicit wait and its usage:
Suppose if a page is getting loaded as follows:
  1. Initially page is loaded
  2. Some tuple/elements are loading through ajax
In this scenario if our script is trying to find some element (which come through ajax call) then we may face exceptions like “ElementNotFound”. This occurs even when we have implemented implicit wait. To avoid such test case failures we can use webdriverwait.
What happens if we use both implicit wait and WebdriverWait:
Suppose we are trying to find a non-existing element on a page
Case 1: Explicit wait time is less than Implicit Wait time
The explicit wait maximum elapsed time is mentioned as 10 seconds and Implicit Time mentioned as 20 seconds. In this case, time taken to find an element is 20 seconds. You can see the code below for the reference.
void TC_Compare_Implicit_ExplicitWait_WhenEXplicit_IsLessthanExplicitWait()
{
      driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
      driver.get(“http://www.naukri.com”);
      String date1=Calendar.getInstance().getTime().toString().replaceAll(“:”, “”);
      System.out.println(date1);
      WebDriverWait wait = new WebDriverWait(driver, 10);
      try
      {
      wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(RP_Homepage.BuyNow_Btn)      ));
      }
      catch(Exception e)
      {
      String date2= Calendar.getInstance().getTime().toString().replaceAll(“:”, “”);
      System.out.println(date2);
      }
}
This code will give two date and time as output. And when you subtract these, it will 20 seconds. Here, wait time is mostly equal to implicit wait time.
Case 2: Explicit wait time is greater than Implicit Wait
The explicit wait maximum elapsed time is mentioned as 20 and Implicit Time is mentioned as 10 . In this case, time taken to find an element is 21 seconds. You can see the code below for the reference.
void TC_Compare_Implicit_ExplicitWait_WhenEXplicit_IsgreaterthanExplicitWait()
{
      driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
      driver.get(“http://www.naukri.com”);
      String date1=Calendar.getInstance().getTime().toString().replaceAll(“:”, “”);
      System.out.println(date1);
      WebDriverWait wait = new WebDriverWait(driver, 20);
      try
      {
            wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(RP_Homepage.BuyNow_Btn)      ));
      }
      catch(Exception e)
      {
            String date2= Calendar.getInstance().getTime().toString().replaceAll(“:”, “”);
            System.out.println(date2);
      }
}
This code will give two date and time as output. And when you subtract these, it will around 21 seconds. Here, wait time is mostly equal to explicit wait time. However in some cases, wait time may exceed mentioned explicit wait time.
 
Conclusion:In this blog I have tried to explain the wait in Selenium using the examples we have used in our automation suite in Naukri. The best used wait is WebDriver wait which solves many problems of ours.
Happy Automation Folks!!!