Skip to main content

Command Palette

Search for a command to run...

Why never use Thread.sleep() in Selenium.

Published
2 min read
Why never use Thread.sleep() in Selenium.
C

SDET | Writing about test automation, Java, Selenium, and everything in between. Helping devs build better software through clean, reliable testing.

When I first began my journey with Selenium automation, Thread.sleep() felt like a handy tool.
Just add Thread.sleep() and the timing issues would vanish. But later it came at a huge cost.

driver.findElement(By.id("loginButton")).click();
Thread.sleep(5000); 
driver.findElement(By.id("dashboard")).click();

Some tests passed locally but failed in CI servers and network and rendering time varied.
As my test suite grew the execution time took way longer arount 10x more.
If something failed it got hard to debug, whether the issue is due to missing element or sleep time.
It became very hard to maintain as I my test suite kept growing.

After some feedback from the mentors I realized the importance of dynamic waits. I started using Explicit and Fluent waits.

Explicit wait:

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

Fluent Wait:

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

The results observed after using dynamic waits:

  • My suite execution time reduced by 30–50%.

  • There were no unnecessary delays

  • No more random failures in Jenkins or CI runs due to loading time mismatch.

  • Cleaner Code, Better Readability.

When to use what?

Implicit wait: Set once for basic element searches.
Explicit Wait: Wait for specific condition.
Fluent Wait: For custom polling, retries, flaky UIs.

Use Thread.sleep() only when you are debugging or analyzing the application behavior manually.

Today, I rely on smart, dynamic waits that make my tests faster, cleaner, and way more reliable.