Selenium Waits

Because your tests deserve better than Thread.sleep()

Selenium Waits

That One Time Everything Just… Waited

Ever seen a test case pass on your machine but crash and burn on Jenkins like it’s reenacting Titanic?

I did.

Mid-sprint regression. DOM loaded slow. Jenkins failed. The bug? A Thread.sleep() party hardcoded for 3 seconds. Element showed up at 3.1s. Game over.

That’s when I started respecting Selenium waits.

This post? It’s your crash course. But in plain English. No “Moreover”, no “as per best practice”. Just real-deal tester talk over virtual chai.

Let’s Talk About Timing Hell in Selenium

Let’s say your element shows up eventually.

But Selenium? It checks immediately. Doesn’t see it? Boom — NoSuchElementException.

And guess what? Java doesn’t care. The test fails. Your CI dies. Manager frowns.

Selenium waits solve this.

But not all waits are created equal.

3 Waits. 3 Personalities. One Drama.

Each wait type is like a teammate:

Wait Type Personality When to Use
Thread.sleep()
The Drunk Roommate
Quick debugging, emergencies
WebDriverWait
The Chill Middle-Child
95% of your real-world cases
FluentWait
The Over-Thinker Who’s Usually Right
Complex scenarios, flaky UIs, retries

Let’s roast each one properly.

Thread.sleep() — The Drunk Roommate

				
					Thread.sleep(5000);
				
			

You say wait for 5 seconds. It waits. Even if the page was ready at 1.5.

You lose 3.5 seconds. Every. Single. Time.

Multiply that by 100 test cases. Congrats, you just wasted 6 minutes doing nothing.

Yeah, and water boils faster in a pressure cooker. Doesn’t mean it’s ideal.

When it’s okay:
  • You’re debugging something weird
  • You’re testing animations or loading spinners
  • You want your test to pause for visibility
But don’t:
  • Use it in production
  • Chain multiple sleeps
  • Rely on it for dynamic content

WebDriverWait — The Chill Middle-Child

This one actually thinks.

You say “wait up to 10 seconds”. It waits until needed. If the element is there in 3s, it moves on.

				
					WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("search")));

				
			

Way smarter than Thread.sleep().

Pro tip: Wrap your ExpectedConditions in reusable methods for DRY code.

FluentWait — The Control Freak We Secretly Love

Want full control? Retry logic? Ignore exceptions? Custom polling?

Meet FluentWait.

				
					Wait<WebDriver> wait = new FluentWait<>(driver)
    .withTimeout(Duration.ofSeconds(30))
    .pollingEvery(Duration.ofSeconds(2))
    .ignoring(NoSuchElementException.class);

wait.until(driver -> driver.findElement(By.id("login-btn")).isDisplayed());

				
			
What makes FluentWait amazing:
  • You control how often it checks
  • You define which exceptions to ignore
  • You handle weird flaky UIs like a pro

It’s like using a sniper instead of a shotgun.

Explicit Wait vs Implicit Wait — This Part Confuses Everyone

Implicit Wait:
				
					driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));

				
			

Applied globally. Works for every element.

But here’s the twist:

Mixing implicit and explicit waits is risky. It can lead to unpredictable timeouts, stacking issues, and mysterious bugs.

My advice?

❌ Avoid implicit waits altogether if you’re already using WebDriverWait or FluentWait.

TimeoutException. Yeah, That Guy.

You’re waiting.

Selenium is polling.

Still waiting…

Then BOOM — TimeoutException.

Why it happens:

  • Element never appears
  • Wrong locator used
  • You waited for visibility but needed clickability
What to do:
  • Double-check locators
  • Use proper ExpectedConditions (like .elementToBeClickable)
  • Increase timeout sensibly, not blindly

Checklist: Pick the Right Wait (Quick & Dirty)

  • ✅ Quick pause for debugging? → Thread.sleep(1000)

  • ✅ Element may take time? → WebDriverWait

  • ✅ Need retries & ignore errors? → FluentWait

  • ❌ Never stack all three like a code lasagna

🔥 Real Case: The Time Waits Made Me Cry

Sprint Demo Day.

I had automated login. Used Thread.sleep(3000) after clicking “Login”.

Guess what? Backend took 4 seconds. Test failed.

I looked like a clown demoing a test that “sometimes works”.

Later, I switched to:

				
					WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(ExpectedConditions.urlContains("dashboard"));

				
			

Fixed. Stable. Boss smiled.

Lesson: Don’t assume. Wait smart.

Bad Wait vs Good Wait (Template Table)

				
					| Bad Practice                     | Good Practice                          |
|----------------------------------|----------------------------------------|
| Thread.sleep(5000) everywhere    | WebDriverWait with condition           |
| Hard-coded wait in loops         | FluentWait with polling & ignore       |
| Ignoring exception handling      | Use try-catch with meaningful logs     |
| No wait for dynamic elements     | Smart wait strategy + timeout configs  |

				
			

Wait Wrapper: The One Code Pattern That Saves Time

Don’t copy-paste wait logic.

Create a utility wrapper.

				
					public class WaitHelper {
    private WebDriver driver;

    public WaitHelper(WebDriver driver) {
        this.driver = driver;
    }

    public WebElement waitForElement(By locator, int timeout) {
        return new WebDriverWait(driver, Duration.ofSeconds(timeout))
                .until(ExpectedConditions.visibilityOfElementLocated(locator));
    }
}

				
			

Then use:

				
					new WaitHelper(driver).waitForElement(By.id("search"), 15);

				
			

Less clutter. More power. Cleaner tests.

Do’s and Don’ts (You’ll Thank Me Later)

✅ Do:
  • Wrap waits in utility classes
  • Use meaningful locators
  • Prefer WebDriverWait for most use cases
  • Log when waits fail for easy debugging
❌ Don’t:
  • Mix implicit + explicit waits
  • Use Thread.sleep() in final tests
  • Forget to poll in FluentWait
  • Blindly copy stack overflow code

FAQs

You might be using the wrong condition. visibilityOfElementLocated() fails if the element is hidden. Try presenceOfElementLocated() to check if it’s in the DOM, regardless of visibility.

WebDriverWait is just a simplified version of FluentWait. FluentWait gives you more control (polling frequency, exception ignoring, etc.). WebDriverWait is perfect for 90% of use cases though.

Use ExpectedConditions.invisibilityOfElementLocated() or wait for the next stable DOM state. These blink-and-you-miss-it elements are why FluentWait exists.

Yes — that’s what driver.manage().timeouts().implicitlyWait() does. But avoid using it with WebDriverWait, or you might end up in timeout hell.

Use:

wait.until(ExpectedConditions.alertIsPresent());

Easy. No need to use sleeps or polling hacks.

It’s Selenium’s way of saying, “Bro, I waited, and still nothing.” Check your locators, expected conditions, and page load behavior. And always confirm the element exists manually first.

Java Script

new WebDriverWait(driver, Duration.ofSeconds(10)).until(
webDriver -> ((JavascriptExecutor) webDriver).executeScript("return document.readyState").equals("complete"));

Depends on your app. A good default is 500ms or 1 second. Avoid making it too aggressive — it’ll just eat CPU for no reason.

Absolutely. It’s one of its superpowers

.ignoring(StaleElementReferenceException.class)

Yes! If you have weird UIs or business rules, create your own Function<WebDriver, Boolean> logic to wait for exactly what you want.

Use waits properly. Avoid hardcoded sleeps. Handle AJAX. Avoid racing the DOM. Read this brilliant guide by Sauce Labs for best practices.

wait.until(ExpectedConditions.elementToBeClickable(By.id(“submit”)));


This ensures the element is both visible and enabled.

Not exactly. FluentWait is Java-specific. But in Python, you can mimic it using custom polling loops with WebDriverWait and conditions.

Yes. Create your own custom function inside until() and add logs inside it:

 

driver -> {
System.out.println("Retrying...");
return driver.findElement(By.id("something")).isDisplayed();
}

Heck yes. Waits belong with your page methods, not in your test steps. Keep the waiting logic encapsulated for maintainability and reusability.

Comment Below If You’ve Seen Worse!

Tell me your Selenium horror stories. Or drop that clever FluentWait hack you’re proud of.

Let’s help the next tired QA who’s just one Thread.sleep() away from losing it.

Also Don’t forget to check our blogs.

Table of Contents

Leave a Reply

Your email address will not be published. Required fields are marked *

Copyright © 2025 ScriptNG

Designed by ScriptNG