Middle
What are implicit and explicit waits in Selenium, and when should each be used?
sobes.tech AI
Answer from AI
In Selenium, there are two main types of waits — implicit and explicit.
- Implicit Wait — this sets a global timeout for finding elements. If an element is not found immediately, WebDriver will retry for the specified time before throwing an exception. Example:
// Set implicit wait to 10 seconds
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
- Explicit Wait — waits for a specific condition for a particular element. It allows waiting, for example, until the element becomes clickable or appears on the page. It is used with the WebDriverWait class and ExpectedConditions.
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("submit")));
When to use:
- Implicit wait is convenient to set once for the entire test to handle small delays when searching for elements.
- Explicit wait is better for dynamic elements when you need to wait for a specific state (visibility, clickability, etc.).
Important: it is not recommended to mix both types of waits, as this can lead to unpredictable behavior and increased wait times.