Selenium supports three different types of waits: Implicit Wait, Explicit Wait, and Fluent Wait. I have provided details about these three types of waits with example scripts below for Selenium and Java.
Implicit Wait:
An implicit wait is designed to wait for the specified amount of time in Selenium. Even if the web element is identified before the wait time expires, the script will not continue execution until the wait time is completed. This is a drawback of the implicit wait.
Example Script:
WebDriver driver = new ChromeDriver();
driver.get("https://example.com");
// Implicit wait
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
Explicit Wait:
An explicit wait continues test execution as soon as the web element is found, even if it is before the specified time. Hence, it is a suitable wait for handling dynamically loaded objects.
Example Script:
WebDriver driver = new ChromeDriver();
driver.get("https://example.com");
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
// Wait until the element is visible wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("username")))
.sendKeys("testuser");
Fluent Wait:
A fluent wait checks for a web element at defined polling intervals and continues execution once the element is identified in Selenium. Fluent Wait allows us to ignore exceptions during the wait period.
Example Script:
WebDriver driver = new ChromeDriver();
driver.get("https://example.com");
Wait<WebDriver> wait = new FluentWait<>(driver)
.withTimeout(Duration.ofSeconds(20))
.pollingEvery(Duration.ofSeconds(2))
.ignoring(NoSuchElementException.class);
WebElement username = wait.until(driver ->
driver.findElement(By.id("username")));
username.sendKeys("testuser");