How to ask the Selenium-WebDriver to wait for few seconds in Java?
Last Updated :
04 Mar, 2024
An open-source framework that is used for automating or testing web applications is known as Selenium. There are some circumstances when the particular component takes some time to load or we want a particular webpage to be opened for much more duration, in that case, we ask the Selenium web driver to wait for a few seconds. In this article, we will discuss the same.
What is Selenium WebDriver?
An automated driver that provides a programming interface for interaction with elements on web pages, thus enabling automated testing of web applications across different browsers and platforms is known as a Selenium web driver. It allows users the features such as automation, cross-browser compatibility implicit and explicit wait, etc.
How to Ask the Selenium-WebDriver to Wait for a Few Seconds in Java?
There are 3 ways to ask the Selenium-WebDriver to wait for a few seconds in Java. These are:
1. Using Sleep Function
The function that stops the execution of the script for a specified amount of time is known as the sleep function. The worst part of the sleep function is that it introduces unnecessary delays in case the user is adding sleep just for loading of previous element. In this method, we will see how we can ask the Selenium web driver to wait using the sleep function.
Syntax:
Thread.sleep(milliseconds); Here, milliseconds: These are the number of milliseconds the user wants the Selenium webdriver to wait.
Example: In this example, we have opened the GeeksForGeeks website, and then we have asked the Selenium driver to wait for 5 seconds using the sleep function before closing the Chromedriver.
Java
//using sleep function
// Importing selenium libraries
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class selenium5 {
public static void main(String[] args) throws InterruptedException {
// State the chromedriver URL
System.setProperty("webdriver.chrome.driver","C:\\Users\\Vinayak Rai\\Downloads\\chromedriver-win64\\chromedriver-win64\\chromedriver.exe");
// Define and initiate the chrome driver
WebDriver driver = new ChromeDriver();
// Open the Geeks For Geeks website
driver.get("https://www.geeksforgeeks.org/");
// Sleep for 5 seconds
Thread.sleep(5000);
driver.quit();
}
}
Output:

2. Using Implicit Wait
- A framework that lets the webdriver wait a certain amount of time before throwing the NoSuchElementException error is known as implicit wait. This can be achieved using the inbuilt functions in Selenium, i.e., implicitlyWait.
- The implicitwait function sets the amount of time the WebDriver instance should wait in case an element webdriver is finding if it's not immediately available.
Syntax:
driver.manage().timeouts().implicitlyWait(seconds, TimeUnit.SECONDS); Here, seconds: These are the number of seconds the user want Selenium webdriver to wait.
Example: In this example, we have opened the GeeksForGeeks website and then asked the Selenium driver to wait for 5 seconds before throwing the NoSuchElementException error.
Java
//using implicit wait
//Importing selenium libraries
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class selenium6 {
public static void main(String[] args) throws InterruptedException {
// State the chromedriver URL
System.setProperty("webdriver.chrome.driver","C:\\Users\\Vinayak Rai\\Downloads\\chromedriver-win64\\chromedriver-win64\\chromedriver.exe");
// Define and initiate the chrome driver
WebDriver driver = new ChromeDriver();
// Open the Geeks For Geeks website
driver.get("https://www.geeksforgeeks.org/");
// Sleep for 5 seconds
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.quit();
}
}
Output:

3. Using Explicit Wait
The way of telling Selenium webdriver to wait for a certain amount of time before throwing any exception is known as explicit wait. It is the most efficient way of asking Selenium webdriver to wait until the element is loaded. It can be achieved using the inbuilt functions of Selenium:
1. WebDriverWait: The method that lets the webdriver wait for a certain condition to be met before execution of the next element is known as the WebDriverWait function.
Syntax:
WebDriverWait wait = new WebDriverWait(driver,Duration.ofSeconds(seconds)); Here, seconds: These are the number of seconds the user want Selenium webdriver to wait.
2. ExpectedConditions.visibilityOfElementLocated: It lets the chromedriver wait for a certain time before the specific element is visible to the webdriver or user.
Syntax:
wait.until(ExpectedConditions.visibilityOfElementLocated(By.linkText(content))); Here, content: It is the content that needs to be loaded before execution of the next element.
Example: In this example, we have opened the GeeksForGeeks website and then asked the Selenium driver to wait for 5 or more seconds before finding an element.
Java
//using explicit wait
//Importing selenium libraries
import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class selenium7 {
public static void main(String[] args) throws InterruptedException {
// State the chromedriver URL
System.setProperty("webdriver.chrome.driver","C:\\Users\\Vinayak Rai\\Downloads\\chromedriver-win64\\chromedriver-win64\\chromedriver.exe");
// Define and initiate the chrome driver
WebDriver driver = new ChromeDriver();
// Open the Geeks For Geeks website
driver.get("https://www.geeksforgeeks.org/");
// Sleep for 5 seconds
WebDriverWait wait = new WebDriverWait(driver,Duration.ofSeconds(5));
wait.until(ExpectedConditions.visibilityOfElementLocated(By.linkText("Data Structures & Algorithms")));
driver.quit();
}
}
Output:

Comparison of Different Wait Methods
In the following table, we have compared the various sleep methods, implicit wait, explicit wait, and sleep function.
Parameters
| Sleep Function
| Implicit Wait
| Explicit Wait
|
---|
Wait time
| It makes the web driver wait for the specified time, irrespective of whether the element is found or not.
| It does not make web drivers wait for the complete duration of time. If the element is found before the duration specified, it moves on to the next line of code execution.
| It makes the web driver stop the execution of the script based on a certain condition for a specified amount of time.
|
---|
Loading of element
| As you don't know how much time will the element take to load so you have to predict the sleep function time unless that works.
| In implicit wait, you can enter the maximum time you think an element will take to load, it loads earlier, and then the next line will be executed automatically.
| In explicit wait, it is not necessary to enter the time, once the element is loaded, the next line is automatically executed.
|
---|
NoSuchElementException error
| It throws a NoSuchElementException error in case the element is not found after the sleep of the web driver is completed.
| The NoSuchElementException error is thrown in case the element is not found in the specified time set by the user.
| There is no chance of a NoSuchElementException error here as the next line is executed only when the element has been loaded properly.
|
---|
Best Practices for Waiting in Selenium-WebDriver
- Avoid sleep function: As the sleep function does not execute the next lines of code until the specified time is over, thus it adds unnecessary delays. Therefore, it is better to avoid sleep function.
- Use Explicit Waits Wisely: The explicit wait is the best waiting technique, still, it is recommended to use it wisely as excessive use of waits can slow down your tests.
- Optimize Timeout Values: It is very crucial to set proper time with sleep and implicit wait function depending on factors like network, loading of website, etc.
- Constantly Review and Enhance Waiting Techniques: The user should review the automation script at regular intervals and modify the waiting techniques, if necessary.
- Use Page Object Model: In case of the huge scripts, it is necessary to follow the page object model as it encapsulates waiting logic within page objects and makes tests more readable and maintainable.
Handling Dynamic Elements with Waiting Strategies
- Explicit Waits: In the case of dynamic elements, explicit wait works best as it makes the script wait until it is necessary to make that element visible and clickable.
- Identify Stable Locators: It is suggested to use the locators that are expected not to change to find an element. This will reduce your effort of changing the script again and again and make it more dynamic.
- Retry Mechanisms: If you are executing a script on a large scale, then don't forget to add a retry mechanism too in the script as it will reduce the failure of the script.
- Fluent Waits: This wait is almost similar to explicit wait, but it is useful while polling as it provides users the flexibility in defining polling intervals.
- Custom Wait Conditions: In case, you don't wait to use any of the above-stated waiting methods, then you can create your waiting method by using if-else conditions for checking if the element is loaded or not.
- Impact on Test Execution Time: As the user wants the script to be executed in minimum time with much efficiency, thus it is necessary to optimize the wait time. This can be done by reducing the wait or giving the necessary time to wait only.
- Network Latency: This is one of the most crucial factors as less network latency increases the script execution time. Thus, it's better to connect to a good internet for running the test.
- Resource Consumption: As implicit and explicit waits continuously keep on checking if the element is found or not, thus it consumes many resources. Therefore, it is recommended to monitor resource usage during test execution.
- Browsing Cache: The temporary files which get stored in the browser are known as browsing cache. It can be very crucial as the data already loaded once will not be loaded again, thus increasing performance.
- Parallel Execution: The multiple scripts can be run at the same time across multiple threads to reduce overall test execution time.
Conclusion
We can say, most commonly, the user wants the selenium web driver to wait until the element is loaded, thus the explicit wait is the best approach as it lets the web driver wait only until the element is found. Also, it eliminates the chance of the web driver throwing the NoSuchElementException error. I hope the various ways mentioned in the above article will help you do your work smoothly.
Similar Reads
How to Take a Screenshot in Selenium WebDriver Using Java?
Selenium WebDriver is a collection of open-source APIs used to automate a web application's testing. To capture a screenshot in Selenium, one must utilize the Takes Screenshot method. This notifies WebDriver that it should take a screenshot in Selenium and store it. Selenium WebDriver tool is used t
3 min read
How to get text from the alert box in java Selenium Webdriver?
In Automation testing, we can capture the text from the alert message in Selenium WebDriver with the help of the Alert interface. By default, the webdriver object has control over the main page, once an alert pop-up gets generated, we have to shift the WebDriver focus from the main page to the alert
3 min read
How do I set the Selenium webdriver get timeout using Java?
Setting timeouts is important for good automated testing in Selenium WebDriver. One important timeout is page load timeout. This controls how long Selenium waits to load a page when visiting a given URL. If there is no timeout, tests may be stuck when pages load slowly. This results in failed tests.
2 min read
How to Install Selenium WebDriver on Windows for Java?
Selenium is an open-source tool for automating testing of web applications which is free and it supports various programming languages such as C#, Java, Perl, PHP, Python, and Ruby. Selenium Webdriver is most well known or you can say famed with Java as of now. In this article, we will look into how
3 min read
How to navigate back to current page from Frame in selenium webdriver using Java?
When automating tests in Selenium WebDriver using Java, working with frames can be tricky. Frames are separate sections within a webpage that operate independently of the main content. Navigating between frames and the main page is a common task in web automation testing. Understanding how to switch
3 min read
How to set Proxy in Firefox using Selenium WebDriver?
In todayâs fast-paced digital world, ensuring that web applications are tested under various network conditions is crucial. Setting up a proxy in Firefox using Selenium WebDriver allows testers to capture traffic, simulate different network environments, and comply with strict corporate policies, ma
4 min read
How to Click on a Hyperlink Using Java Selenium WebDriver?
An open-source tool that is used to automate the browser is known as Selenium. Automation reduces human effort and makes the work comparatively easier. There are numerous circumstances in which the user wants to open a new page or perform a certain action with the click of the hyperlink. In this art
4 min read
How to Select Value from DropDown using Java Selenium Webdriver?
In web Automation testing, the common task is Selecting the Dropdowns. Selenium Webdriver mainly used for Interacting to the Web-Elements. Selecting the Web-Elements from the dropdowns is a needed for the interaction to the browser. In these guide we will going through the process of selecting the d
2 min read
How to upload a file in Selenium java with no text box?
Uploading a file in Selenium Java without a visible text box can be easily handled using the sendKeys() method. Even if the file input field is hidden or styled as a button, Selenium allows you to interact with it by providing the file path directly. This method simplifies the process of file upload
3 min read
How to do session handling in Selenium Webdriver using Java?
In Selenium WebDriver, managing browser sessions is crucial for ensuring that each test runs independently and without interference. A browser session in Selenium is identified by a unique session ID, which helps track and manage the session throughout the test. Proper session handling in Selenium W
4 min read