How To Use Thread.sleep Java With Selenium?

Shalini Baskaran

Posted On: October 8, 2020

view count84566 Views

Read time15 Min Read

Automating a web application optimizes the work, helps minimize errors and makes the product robust. An automated suite would be successful when the behaviour is predictable. If not so, there would be many hurdles in automation that need to be handled carefully. Sometimes while automating a web application, we may face an exception NoSuchElementException, which is thrown when the element that is being interacted with is not found. This may look weird when you can actually see the element on the webpage, but it has vanished during Selenium test automation.

The principal cause of this exception is that the element to be interacted with actually exists in the page but takes time to load and display itself to the user. As you can imagine, this can turn out to be a major issue during automation and can lead our scripts ashtray. This is where Thread.sleep() in Selenium Java comes into play. Before we look into the effective use of Thread.sleep() Java function, let us understand the basics about Thread.sleep() in Selenium.

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. Implicit wait- This wait allows you to halt the WebDriver for a specific period of time until the WebDriver is able to locate a desired element on a web page.
  2. Explicit wait- This wait allows you to stop the execution of a script based on a preset condition for a specific amount of time.

However, there are a few instances where Thread.sleep() would be considered a better choice.

Thread.sleep() is a static Java method that suspends the code for a specific amount of time. It pauses the execution and helps us to know what has happened during the pause. It accepts the time specified in milliseconds. This function is particularly helpful for debugging a website or web page. And this should not be confused with the Selenium waits mentioned above. We will dig deeper into the difference between Thread.sleep() Java & Selenium waits in the next sections.

Below is the syntax for Thread.sleep() Java-

While using this method, you may face a common exception – InterruptedException which has to be handled either by using throws or try catch block as shown below-

In the next sections, we will understand why and how to use Thread.sleep() in Java, first; let’s take a look at why Thread.sleep() Java is used in Selenium test automation.

This certification demonstrates your knowledge of Selenium and Java, and your expertise at automating tests for any project.

Here’s a short glimpse of the Selenium Java 101 certification from LambdaTest:

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.

Instead of making the code complex with below lines, we can use Thread.sleep() for some amount of time which reduces the complexity.

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.

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.

As expected, easemytrip.com will take some time to load the relevant flight details. To avoid this delay in our script, we will be stopping the thread execution as soon as the user clicks on ‘Search.’ Once we do this, you will see that the script will run smoothly, without throwing an exception or error.

Here’s the code snippet-

Let us consider another instance. What if we have another web page on easemytrip.com that takes less or more than the specified amount of time to load? The time spent on locating the element is simply not considered when it comes to Thread.sleep() in Selenium Java because it is a static wait. Selenium WebDriver will have no choice but to wait for the specified time, regardless of the fact that the element has been located or not. This is why we prefer not to use Thread.sleep() multiple times in our automation scripts.

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()?’

Well, Thread.sleep() has been provided by Java but when used in the automation scripts, it is often considered to be unstable. Ideally, it is not recommended to use Thread.sleep() in our scripts as it may increase the test execution time (as explained in the last section). Although, while executing tests with third-party interfaces and AJAX calls might always seem to be complex which when handled wisely with the proper wait like Thread.sleep() will ease the execution with high accuracy results.

If that’s not the case with you, you might be better off using other Selenium waits like Implicit Wait, Explicit Wait or Fluent Wait. You can refer to this tutorial for using Explicit and Fluent Wait in Selenium.

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-

  • Sleep is a static method that belongs to the ‘Thread’ class of Java. On the other hand, Implicit, Explicit & Fluent Selenium waits are dynamic in nature.
  • 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.

Selenium setSpeed() is basically used to set a specific speed of execution. When running a script in Selenium, there is no delay by default. With the help of setSpeed(), we can set the length of delay (in milliseconds) which will then be followed by each execution in that Selenium script.

To put it plainly, Thread.sleep() makes the WebDriver wait for a specific time before execution and this happens only once. On the other hand, setSpeed() sets the desired speed of execution or delays execution by a specified amount of time before each operation.

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.

Let us know if you have come across any other scenarios where you have found a better way to effectively implement this method. Also, if you have any questions, feel free to reach out to us via the comment section below.

Happy Testing!

Run Selenium Java Test

Frequently Asked Questions (FAQs)

What is thread sleep in Java?

Thread.sleep() provides an effective approach to temporarily suspend the execution of the current thread, enabling processor resources to be efficiently allocated to other threads within an application or parallel applications running on a computer system. This aids in optimizing resource utilization and enhancing system performance without relying on AI-generated content.

What is thread sleep 1000 in Java?

The Java Thread.sleep() function provides a simple way to briefly suspend the current thread’s execution for a predetermined amount of time, measured in milliseconds.

What is yield () and sleep () in thread Java?

Java’s sleep() function, which temporarily halts the operation, can be utilized to put a running thread into a sleeping state. But the yield() method stops the current thread object, giving the other threads time to continue operating.

What is wait vs thread sleep?

While sleep() is intended to momentarily interrupt work in Java, wait() encourages communication between threads. The sleep() function places the active thread in the “Not Runnable” state for a predetermined period of time.

Is thread sleep static or dynamic?

Thread sleep is static in Java because it allows for the precise suspension of function execution for a predetermined amount of time.

What are the advantages of thread sleep?

By including a Thread.sleep() statement, you may force a wait in your test until the desired condition is satisfied. This proactive approach helps to lessen errors or failures brought on by synchronization or timing problems.

Is thread synchronous or asynchronous?

By utilizing the capabilities of numerous threads, async, sometimes referred to as asynchronous, enables the execution of activities or programs in parallel. A single operation or programs is guaranteed to run at a time while using sync, also known as synchronized operation. Because async is non-blocking, it effectively dispatches many requests to a server at once, which is a considerable benefit.

What is sleep () in Java?

The “sleep()” function in Java halts the current thread’s execution for a designated duration. It’s a useful way to share CPU resources among threads or other applications running on a computer.

How does sleep () work?

The sleep() function pauses execution for a specified time in seconds, or until a signal arrives. It returns 0 if the time interval elapses and the program resumes. If interrupted by a signal, it returns the remaining time left in the sleep interval.

How to use thread sleep () in Java?

To use Thread.sleep() in Java, call the method inside a thread’s run() function. Specify the time in milliseconds for the thread to sleep. If an interruption occurs, catch InterruptedException. This example sleeps the thread for 500 milliseconds in a loop, printing the count.

What is sleep vs suspend in Java?

Sleep in Java pauses the execution of a thread for a designated duration. On the other hand, suspend halts a thread until it’s manually resumed, potentially leading to thread-related issues due to its unpredictability and possible deadlock risks.

Author Profile Author Profile Author Profile

Author’s Profile

Shalini Baskaran

Shalini works as a Technical Writer at LambdaTest. She loves to explore recent trends in test automation. Other than test automation, Shalini is always up for travel & adventure.

Blogs: 20



linkedintwitter

Test Your Web Or Mobile Apps On 3000+ Browsers

Signup for free