Skip to main content

Command Palette

Search for a command to run...

Synchronization in Selenium java

Published
β€’5 min readβ€’View as Markdown

βœ… What is Synchronization in Selenium (Java)?


πŸ”Ή Definition:

Synchronization in Selenium (Java) is the process of matching the speed of your automation script with the speed of the web application so that your script waits for the elements to load, appear, or become ready for interaction before performing actions on them.


πŸ”Ή Why Synchronization is Needed:

  • Web elements may take time to load due to AJAX, JavaScript, animations, or slow networks.

  • Without waiting, Selenium might try to interact with an element that:

    • is not yet present,

    • is not visible or clickable,

    • or is still being updated in the DOM.

This causes errors like:

  • NoSuchElementException

  • ElementNotInteractableException

  • StaleElementReferenceException

To avoid such kind of exceptions we using wait statements.

Types of Waits in Selenium

Selenium provides 3 main types of waits:

Wait TypeUse CaseApplies To
Implicit WaitWaits globally for elements to appear.All elements
Explicit WaitWaits for a specific condition on a specific element.Single element or condition
Fluent WaitLike Explicit Wait but allows polling and exception handling.Advanced conditions

1️⃣ Implicit Wait

Tells WebDriver to wait for a certain amount of time when trying to find an element if it is not immediately available.

πŸ”Έ Syntax:

javaCopyEditdriver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));

πŸ”Έ Key Points:

  • Applies globally to all elements.

  • Doesn't wait for a condition, only presence in DOM.

  • Not recommended for dynamic web apps (use explicit instead).


2️⃣ Explicit Wait

Waits for a specific condition (like visibility or clickability) before throwing an exception.

πŸ”Έ Common Conditions (ExpectedConditions):

  • visibilityOfElementLocated(By)

  • elementToBeClickable(By)

  • presenceOfElementLocated(By)

  • alertIsPresent()

  • titleContains(String)

  • frameToBeAvailableAndSwitchToIt()

πŸ”Έ Syntax:

javaCopyEditWebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(15));
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("username")));

3️⃣ Fluent Wait

A more flexible version of Explicit Wait that allows:

  • Custom polling interval

  • Ignoring specific exceptions (e.g., NoSuchElementException)

πŸ”Έ Syntax:

javaCopyEditWait<WebDriver> fluentWait = new FluentWait<>(driver)
    .withTimeout(Duration.ofSeconds(20))
    .pollingEvery(Duration.ofMillis(500))
    .ignoring(NoSuchElementException.class);

WebElement element = fluentWait.until(driver -> driver.findElement(By.id("username")));

πŸ“‹ Full Cheat Sheet: Wait Type Comparison

FeatureImplicit WaitExplicit WaitFluent Wait
Applies ToAll elementsSpecific elementsSpecific elements
Custom ConditionsβŒβœ…βœ…
Polling IntervalFixedFixedCustomizable
Exception HandlingβŒβŒβœ…
Recommended❌ (for dynamic apps)βœ…βœ… (advanced use cases)

🧠 Best Practices

  1. βœ… Prefer Explicit Waits over Implicit.

  2. ❌ Avoid mixing Implicit and Explicit Waits β†’ can lead to unexpected timeout behavior.

  3. βœ… Use ExpectedConditions for readable and maintainable code.

  4. βœ… Use FluentWait when:

    • You want custom polling intervals.

    • You want to ignore multiple exceptions.


πŸ’‘ Example: Wait for Login Button to Be Clickable

javaCopyEditWebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement loginBtn = wait.until(ExpectedConditions.elementToBeClickable(By.id("loginButton")));
loginBtn.click();

🚨 Common Exceptions with Waits

ExceptionReason
TimeoutExceptionCondition not met within timeout.
NoSuchElementExceptionUsed without wait or condition wrong.
StaleElementReferenceExceptionDOM refreshed, element became stale.

πŸ§ͺ Bonus: Waiting for Page Load (JS Ready State)

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

Would you like a downloadable PDF/Excel version of this Waits Cheat Sheet or sample framework code with all types of waits implemented?

You said:

what is synchronization in java selenium

ChatGPT said:

βœ… What is Synchronization in Selenium (Java)?

Synchronization in Selenium refers to matching the speed of your automation script with the speed of the web application so that your test scripts do not fail due to timing issues.


🚦 Why Synchronization is Needed?

Web applications are dynamic. Some elements take time to:

  • Load

  • Become clickable

  • Appear/disappear

  • Respond to JavaScript or AJAX calls

If Selenium tries to interact with an element before it's ready, it can throw exceptions like:

ExceptionReason
NoSuchElementExceptionElement not yet in DOM
ElementNotInteractableExceptionElement not ready for interaction
StaleElementReferenceExceptionElement detached from DOM

πŸ› οΈ Types of Synchronization in Selenium

πŸ”Ή 1. Implicit Wait – Global sync

javaCopyEditdriver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
  • Waits for element to appear in DOM.

  • Works for all findElement calls.

  • Not condition-based.


πŸ”Ή 2. Explicit Wait – Targeted sync

javaCopyEditWebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(15));
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("submit")));
  • Waits for specific condition.

  • Better control than implicit wait.


πŸ”Ή 3. Fluent Wait – Advanced sync

javaCopyEditWait<WebDriver> fluentWait = new FluentWait<>(driver)
    .withTimeout(Duration.ofSeconds(20))
    .pollingEvery(Duration.ofMillis(500))
    .ignoring(NoSuchElementException.class);
  • Custom polling.

  • Ignore specific exceptions.


πŸ”Ή 4. Thread.sleep() – Forced sync

javaCopyEditThread.sleep(3000); // pauses execution for 3 seconds
  • Pauses script no matter what.

  • Not recommended (makes test slower and less reliable).


πŸ“Š Synchronization Comparison

TypeControlDynamic?Reliable?Usage
Thread.sleep❌❌❌Avoid
Implicit Wait❌⚠️⚠️Simple pages
Explicit Waitβœ…βœ…βœ…Recommended
Fluent Waitβœ…βœ…βœ…βœ…βœ…βœ…Complex scenarios

πŸ“Œ Example: Synchronization Failure Without Wait

javaCopyEditdriver.findElement(By.id("searchBox")).sendKeys("laptop");  // Might fail if not loaded yet

βœ… With Explicit Wait

javaCopyEditWebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement searchBox = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("searchBox")));
searchBox.sendKeys("laptop");

πŸ’‘ Summary

TermMeaning
SynchronizationMatching script and app timing
GoalAvoid timing-related failures
Best PracticeUse explicit or fluent wait (not Thread.sleep)

More from this blog

Shreenibas Samal's blog

49 posts