ScreenshotNeo

BlogHow-to

How to Use Thread.sleep() in Selenium with Java

Learn the Java syntax for pausing a Selenium test, when Thread.sleep() is useful, and how to replace fixed delays with explicit waits.

By the ScreenshotNeo team4 October 20267 min read

Thread.sleep(1000); pauses the current Java thread for about one second. In a Selenium test, you can put it between an action and the next browser command, but it does not check whether the page is ready. For a test that depends on a particular element or page state, Selenium explicit waits are usually the better choice.

1. Basic Thread.sleep() syntax

Thread.sleep is a static method on Java’s Thread class. Its argument is a duration in milliseconds, so Thread.sleep(1000) requests a pause of one second. The method throws InterruptedException, which your method must handle or declare.

Thread.sleep(1000);

For example, declare the exception on a test method:

import org.junit.jupiter.api.Test;

class SleepExampleTest {
    @Test
    void pauseForOneSecond() throws InterruptedException {
        Thread.sleep(1000);
        // Continue with the test.
    }
}

This demonstrates Java syntax only. A pause with no browser condition is rarely a robust way to synchronize a Selenium test.

2. Use it in a Selenium test

Here is the basic pattern: click a control, pause, then locate content that the action is expected to create. The example uses Selenium Java and JUnit 5; it assumes a driver is available and the page under test contains the stated elements.

import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

class FixedSleepTest {
    @Test
    void clickAndWait() throws InterruptedException {
        WebDriver driver = new ChromeDriver();
        try {
            driver.get("https://example.com");
            driver.findElement(By.id("show-result")).click();

            Thread.sleep(1000);

            String result = driver.findElement(By.id("result")).getText();
            System.out.println(result);
        } finally {
            driver.quit();
        }
    }
}

Replace the URL and selectors with the page’s actual values. The required Java imports are shown, but installing Java, Selenium, a browser, and a compatible driver is outside this timing example. Selenium’s example likewise shows the sleep after an action that creates an element and declares InterruptedException. Selenium WebDriver documentation

3. What Thread.sleep() does—and does not do

  • It pauses the current thread. Selenium commands later in that same test do not run until the sleep returns.
  • It waits for time, not state. It does not inspect the DOM, network activity, or whether a control is clickable.
  • The requested time is not a readiness guarantee. If the page takes longer, the next command can still fail. If the page is ready sooner, the test still waits out the full interval.
  • It can slow repeated test runs. Fixed delays add their full duration each time they run, even when no delay was needed.

Selenium describes both risks: a delay can be too short for the page and cause the next command to fail, or unnecessarily long and extend the session. Selenium: Waiting Strategies

4. Prefer an explicit wait for browser state

An explicit wait polls for a specific condition and continues as soon as it succeeds, up to a timeout. Choose a condition that represents what the next test step actually needs: presence, visibility, clickable state, expected text, or a title change.

import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.WebDriverWait;

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement result = wait.until(
    d -> d.findElement(By.id("result"))
);

The lambda above waits until finding the element succeeds. If the next action requires the element to be visible, use that condition instead:

import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOfElementLocated;

WebElement result = wait.until(
    visibilityOfElementLocated(By.id("result"))
);

For a click that should only happen once a control can be interacted with:

import static org.openqa.selenium.support.ui.ExpectedConditions.elementToBeClickable;

WebElement continueButton = wait.until(
    elementToBeClickable(By.id("continue"))
);
continueButton.click();

Use the condition that matches the next operation. Presence alone does not establish visibility or clickability. Selenium’s expected-condition guidance also covers staleness, visible text, and title matching. Selenium explicit waits and expected conditions

5. Implicit waits and why not to mix wait strategies

An implicit wait is configured once on the driver and applies to element-location calls throughout the session. Its Java API accepts a Duration:

import java.time.Duration;

driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(2));

Explicit waits are local to a condition; implicit waits affect element searches session-wide. Selenium warns against combining implicit and explicit waits because the total timing can become unpredictable. For example, a 10-second implicit wait combined with a 15-second explicit wait may time out after 20 seconds rather than 15. Prefer one deliberate strategy—typically explicit waits for the states a test depends on. Selenium: Waiting Strategies

6. Handling InterruptedException

Thread.sleep declares InterruptedException. At a test-method boundary, you can declare it with throws InterruptedException, as in the examples above. If you catch it inside application or utility code, preserve the thread’s interrupted status when you cannot propagate the exception:

try {
    Thread.sleep(1000);
} catch (InterruptedException e) {
    Thread.currentThread().interrupt();
    throw new IllegalStateException("Pause was interrupted", e);
}

Do not silently swallow the exception. An interrupt is a signal that the waiting thread should stop or handle cancellation, and ignoring it can make shutdown or cancellation behavior harder to reason about.

7. When a fixed sleep is useful

A short hard-coded sleep can be a temporary diagnostic. If adding one makes a flaky step pass, that suggests the test may be racing a page update. Replace the diagnostic pause with a wait for the specific state the next operation needs. Selenium troubleshooting guidance describes this as a clue for synchronization problems; its test-authoring guidance says, “Never sleep in a test.” Selenium troubleshooting · Selenium test practices

8. Troubleshooting

Symptom Likely cause What to do
Unhandled exception: InterruptedException at compile time Thread.sleep declares a checked exception. Declare throws InterruptedException on the test method or catch it and preserve interruption as shown above.
NoSuchElementException after the sleep The fixed duration ended before the element appeared, or the locator is wrong. Verify the locator and use an explicit wait for presence or visibility of that element.
ElementNotInteractableException or click failure The element may exist but not yet be visible or clickable. Wait for visibility or clickability, and check for overlays or disabled state.
The test is slow despite passing Every execution pays the entire fixed delay. Replace the sleep with an explicit wait that returns as soon as its condition is true.
Timeout duration seems longer than configured Implicit and explicit waits may be interacting. Do not mix the strategies; remove the session-wide implicit wait when relying on explicit conditions.
The sleep is interrupted The waiting thread received an interrupt. Propagate the exception or restore the interrupt flag and stop the operation; do not ignore it.

9. Performance, reliability, and cost notes

  • Performance: fixed sleeps always consume their configured duration. Explicit waits can finish earlier when the condition becomes true, while still providing a timeout bound.
  • Reliability: a sleep hides the condition the test depends on and can fail under different page or machine timing. A condition-specific wait makes that dependency explicit.
  • Timeout choice: set a bounded timeout suited to the operation, and wait for a meaningful condition. A very long timeout can delay feedback when a real defect exists.
  • Test cost: avoid adding arbitrary delays to every test step. Repeated fixed waits increase suite runtime; Selenium’s documentation does not provide a universal runtime saving or flaky-test percentage, so none should be assumed.

10. Or skip the browser setup

If your goal is to capture a page image rather than exercise browser behavior, ScreenshotNeo can return a screenshot with one GET request. It is a website screenshot API and MCP server for developers, made by ScreenshotNeo. The API call can save the browser setup and timing code for this use case. See the ScreenshotNeo API documentation for request options.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests

r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
    timeout=90,
)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`Screenshot request failed: ${res.status}`);
await import('node:fs/promises').then(fs => fs.writeFile('shot.webp', Buffer.from(await res.arrayBuffer())));
  • Cookie banners are accepted and 60+ known consent platforms are removed before capture; newsletter popups and chat widgets are removed too. Each step can be turned off.
  • Bot checks and CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are never billed. Response headers say which page verdict applied and whether the request was billed.
  • An MCP server gives AI agents tools to take screenshots, get page information, and capture PDFs.
  • 1,000 screenshots a month are free with no card. Paid plans start at $5 for 3,000 screenshots.

Sign up for ScreenshotNeo and get 1,000 screenshots a month free, with no card.

11. FAQ

How do I pause Selenium in Java?

Call Thread.sleep(milliseconds), such as Thread.sleep(1000) for a requested one-second pause. It throws InterruptedException.

What should I use instead of Thread.sleep()?

Use WebDriverWait with a condition matching the page state your next step requires, such as visibility or clickability.

Does Thread.sleep() wait for a page to load?

No. It pauses the Java thread for a duration; it does not check whether the page or a particular element has finished loading.

Can I combine implicit and explicit waits?

Selenium advises against mixing them because the resulting total wait can be unpredictable. Choose a consistent wait strategy.