How To Use Thread.sleep() In Java With Selenium ?

Image for post
Image for post

Note: The code samples may be displayed improperly because of markdown. I recommend continuing to read the original article Thread.sleep() Java & Selenium to make sure all the examples are displayed properly.

What Is Thread.sleep()?

To make our scripts less flaky, we have to add waits which will add some waiting time for an element or all the elements in the webpage to load. The implementation of these waits depends on the type of wait chosen in the automation script. The two most commonly used Selenium Waits are-

  1. Explicit wait- This wait allows you to stop the execution of a script based on a preset condition for a specific amount of time.
//Pauses test execution for specified time in milliseconds
Thread.sleep(1000);
try{
Thread.sleep(1000);
}
catch(InterruptedException ie){
}
Orpublic static void main(String args[]) throws InterruptedException{
Thread.sleep(1000);
}

Why Do We Use Thread.sleep() in Selenium?

With web applications getting bigger by the minute, it is no surprise that different applications take different times to load completely. Thread.sleep() plays a pivotal role in including the page load in our Selenium scripts. Using functions like Thread.sleep() Java enables us to run automated tests successfully without coming across any failure of the script. Below are some major reasons why we use Thread.sleep() in Selenium Java-

Handle Dynamic Elements:

There might be times where the application’s webpage has dynamic elements and it will be hard to predict the behaviour. For example, most of the eCommerce websites have carousel/slider design which changes dynamically. Instead of using Selenium waits to check for the visibility of the web element, we can wisely choose Thread.sleep() to wait for a few seconds.

Reduce Code Complexity:

While testing a web page, there is a possibility where the page is loaded, and the execution has moved to the next step, but there wasn’t enough time to select an option in the webpage. In such cases, we can use either Fluent waits to suspend the time until the element is visible in the page or use Thread.sleep(). It is better to choose the latter one as it involves adding a single line of code rather than adding five to six lines of code in Selenium waits. This implementation would avoid unnecessary code complexity.

Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(30, SECONDS)
.pollingEvery(5, SECONDS)
.ignoring(NoSuchElementException.class);
WebElement element = wait.until(new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
return driver.findElement(By.id(“username”));
}
});

Testing Third-Party Systems:

While testing the web pages which interact with the third-party components, we might not know how it was designed. We might not know how long it takes for a web element to be visible in the webpage. Hence predicting the conditions to handle the web elements seems to be complex, sometimes even impossible. In such situations, we can delay the execution time by using Thread.sleep() Java method.

Handle AJAX Calls:

AJAX (Asynchronous JavaScript and XML) is an advanced communication technique where the webpage requests certain information from the server without affecting the current state of the webpage. Thread.sleep() will be one of the best choices to handle the AJAX calls in the web page as the test would wait for a certain period for the server to respond. There are certain web pages where you can see live scores of a cricket or football match. Here, the score gets updated in specific intervals of time while all the other elements in the webpage remain the same. This is an example for AJAX call and how handling it with Thread.sleep() would be one of the better options while executing the tests.

Image for post
Image for post

Using Thread.Sleep() Java For Selenium Test Automation

Now that you understand why Thread.sleep() in Selenium Java is a good choice, this section will show you how to implement the function in Selenium test automation. To showcase its implementation, we are using an example of the website- easemytrip.com. Here, we will show you an instance user selecting the ‘From’ and ‘To’ destination along with a date of journey.

Alternatives To Thread.sleep() Java

People often ask ‘Is it a good practice to use Thread.sleep()?’ or ‘What can I use instead of Thread.sleep()?’

Difference Between Thread.sleep() & Waits

Waits completely ceases the execution thread for a specified amount of time. On the other hand, Thread.sleep() pauses the execution and helps us to know what has happened. But that is not all. Listed below are the key differences between Thread.sleep() Java method & Selenium waits-

  • If you use Thread.sleep while performing Selenium test automation, it will stop the execution of the script for the time specified in the script, irrespective of the fact that the element on the web page has been found. Selenium waits do not wait for the complete duration of time. If the WebDriver is able to find the element before the specified time duration, it moves on to the next line of code. This helps in reducing the overall time of script execution by a considerable margin.
  • Waits are often applied globally i.e. we only need to write it once in the script and it is applicable for all the web elements specified throughout the WebDriver instance. That is not the case with Thread.sleep(), where you are required to write it again for each web element. This makes waits a better option than Thread.sleep() in Selenium Java.

Difference Between Thread.sleep() & Selenium setSpeed()

As we have seen above how to use Thread.sleep() in Java, we understand clearly that it is used to delay the code execution. setSpeed() has a similar role and is also used to delay the over execution. Yet, the two functions are different from each other.

Conclusion

We hope you guys have learned the effective ways of using Thread.sleep() Java method by reading this article. Thread.sleep() Java is a useful method when it comes to web application debugging and can even be implemented with an online Selenium Grid for cross browser testing platforms like LambdaTest.

Author Shalini Baskaran

Written by

Product Growth at @lambdatesting (www.lambdatest.com)

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store