Waits in Selenium

In web application we need to ensure that the flow of the test cases should be in synchronization with the application under test. When we execute our tests, the application may not always behave with the same manner and speed. For example: Sometime it might take few seconds to load the page properly or take time for a button to become enabled or a pop up messsage appear etc. We can handle these timing problems by synchronizing our scripts with waits concepts.

Implicit wait:

An implicit wait set the WebDriver to poll the DOM for a certain amount of time when trying to find an element if they are not immediately available. During Implicit wait if the WebDriver cannot find it immediately, it will keep polling around 250 milli seconds the DOM to get the element. If the element is not available within the specified Time an NoSuchElementException will be raised. The implicit wait is set for the life of the WebDriver object instance.

WebDriver driver => new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.get("http://hugelearning.com");
WebElement element = driver.findElement(By.id("testElement"));

Explicit Wait:

In application sometime there can be instance when a particular element takes more than a minute to load. In that case we would not like to set a long time to Implicit wait, as if we do this our browser will going to wait for the same time for every element.
To avoid this type of situation we can simply put a separate time on the required element only. Inother words like an explicit wait represents a set of code for certain conditions to occur before continued further.

WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.titleContains("huge learning"));

Fluent wait:

FluentWait instance describes the maximum amount of time to wait for a condition, as well as the frequency with which to check the condition. Apart of this, we may configure the wait to ignore specific types of exceptions while waiting for the element(s), such as ‘NoSuchElementExceptions’.

Wait wait = new FluentWait(driver).withTimeout(20, SECONDS).pollingEvery(5, SECONDS).ignoring(NoSuchElementException.class);
wait.until(ExpectedConditions.elementToBeClickable(By.id("testID")));