We wait in tests to let the web page load or elements appear before we interact with them. Using the right wait helps tests run smoothly and avoid errors.
Thread.sleep vs proper waits in Selenium Java
Thread.sleep(milliseconds); WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(seconds)); wait.until(ExpectedConditions.visibilityOfElementLocated(By.locator));
Thread.sleep pauses the test for a fixed time no matter what.
Proper waits wait only as long as needed until a condition is true, making tests faster and more reliable.
Thread.sleep(5000);WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); wait.until(ExpectedConditions.elementToBeClickable(By.id("submitBtn")));
This test opens a page where a button appears after delay. First, it waits 5 seconds using Thread.sleep, then clicks the button. Next, it refreshes and waits properly until the button is clickable, then clicks it. Proper wait is better because it waits only as long as needed.
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import java.time.Duration; public class WaitComparison { public static void main(String[] args) throws InterruptedException { System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); WebDriver driver = new ChromeDriver(); driver.get("https://example.com/delayedButton"); // Using Thread.sleep (bad practice) Thread.sleep(5000); // wait fixed 5 seconds WebElement button1 = driver.findElement(By.id("delayedBtn")); button1.click(); System.out.println("Clicked button using Thread.sleep"); driver.navigate().refresh(); // Using proper wait (good practice) WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); WebElement button2 = wait.until(ExpectedConditions.elementToBeClickable(By.id("delayedBtn"))); button2.click(); System.out.println("Clicked button using proper wait"); driver.quit(); } }
Avoid Thread.sleep because it always waits full time, slowing tests.
Use explicit waits like WebDriverWait for better speed and reliability.
Implicit waits are another option but explicit waits give more control.
Thread.sleep pauses test for fixed time, which can waste time or cause failures.
Proper waits wait only until a condition is met, making tests faster and stable.
Prefer explicit waits like WebDriverWait over Thread.sleep in Selenium tests.