There are many occasion when a wait is required in selenium before performing an operation. For example Waiting for an element to be visible, wait until page load is completed. etc. Following java code with covers most of the common required methods in selenium webdriver.

- Function to wait until Page load is complete
/**
* Function to wait until the page loads completely
*
* @param timeOutInSeconds
* The wait timeout in seconds
*/
public void waitUntilPageLoaded(long timeOutInSeconds) {
WebElement oldPage = driver.findElement(By.tagName("html"));
(new WebDriverWait(driver, timeOutInSeconds)).until(ExpectedConditions.stalenessOf(oldPage));
}
2. Function to wait until the page readyState equals ‘complete’
/**
* Function to wait until the page readyState equals 'complete'
*
* @param timeOutInSeconds
* The wait timeout in seconds
*/
public void waitUntilPageReadyStateComplete(long timeOutInSeconds) {
ExpectedCondition<Boolean> pageReadyStateComplete = new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver driver) {
return ((JavascriptExecutor) driver).executeScript("return document.readyState").equals("complete");
}
};
(new WebDriverWait(driver, timeOutInSeconds)).until(pageReadyStateComplete);
}
3. Function to wait until the specified element is located
/**
* Function to wait until the specified element is located
*
* @param by
* The {@link WebDriver} locator used to identify the element
* @param timeOutInSeconds
* The wait timeout in seconds
*/
public void waitUntilElementLocated(By by, long timeOutInSeconds) {
(new WebDriverWait(driver, timeOutInSeconds))
.until(ExpectedConditions.presenceOfElementLocated(by));
}
4. Function to wait until the specified element is visible
/**
* Function to wait until the specified element is visible
*
* @param by
* The {@link WebDriver} locator used to identify the element
* @param timeOutInSeconds
* The wait timeout in seconds
*/
public void waitUntilElementVisible(By by, long timeOutInSeconds) {
(new WebDriverWait(driver, timeOutInSeconds))
.until(ExpectedConditions.visibilityOfElementLocated(by));
}
5. Function to wait until the specified element is enabled
/**
* Function to wait until the specified element is enabled
*
* @param by
* The {@link WebDriver} locator used to identify the element
* @param timeOutInSeconds
* The wait timeout in seconds
*/
public void waitUntilElementEnabled(By by, long timeOutInSeconds) {
(new WebDriverWait(driver, timeOutInSeconds)).until(ExpectedConditions.elementToBeClickable(by));
}
6. Function to wait until the specified element is disbaled
/**
* Function to wait until the specified element is disabled
*
* @param by
* The {@link WebDriver} locator used to identify the element
* @param timeOutInSeconds
* The wait timeout in seconds
*/
public void waitUntilElementDisabled(By by, long timeOutInSeconds) {
(new WebDriverWait(driver, timeOutInSeconds))
.until(ExpectedConditions.not(ExpectedConditions.elementToBeClickable(by)));
}