The lazy solution: Thread.sleep(3000) — pause for 3 seconds and hope the page loads. Every beginner does this. Every senior will tell you to stop.
// The lazy approach — DON'T do this in production
driver.findElement(By.id("login-btn")).click();
try {
Thread.sleep(3000); // Pause 3 seconds... and pray
} catch (InterruptedException e) {
e.printStackTrace();
}
String balance = driver.findElement(
By.id("account-balance")).getText();If you ever find yourself writing Thread.sleep() in a loop with element checks, stop. You're reinventing WebDriverWait — badly. Use the real thing.
// This is just a bad version of WebDriverWait
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(1000);
WebElement el = driver.findElement(By.id("dynamic-content"));
if (el.isDisplayed()) break;
} catch (NoSuchElementException e) {
// Keep waiting...
}
}
// Use WebDriverWait instead. It does exactly this, but properly.The only time Thread.sleep() is acceptable: quick debugging, or waiting for something that has zero DOM signals (like a file download completing). Even then, try to find a better signal first.
Key Point: Thread.sleep() wastes time when pages are fast and still fails when pages are slow. Use WebDriverWait instead.