Understanding Role of Thread.sleep() in Selenium

On This Page Why do you need wait commands in Selenium?May 18, 2026 · 8 min read · Tool Comparison

Understanding Role of Thread.sleep () in Selenium

An automation framework must be robust and test cases should be written in such a manner that mechanisation test termination are e'er echt. When building Selenium automation trial, flakiness often comes from time issues due to pages or component not full loaded before actions are attempted. While Selenium ’ s implicit and explicit waiting are mostly preferred, there are sure scenarios where neither works well. In such cases, Java ’ s Thread.sleep () is used to hale a pause in executing.

Overview

Types of Selenium Waits

  • Unquestioning wait: Set globally and applied for all find-element operations.
    Explicit wait: Waits for specific conditions on specific ingredient.

When to Use Thread.sleep ()

  • Testing dynamic web component when other waits fail.
    Interactions involving third‐party situation where load clip is irregular.
    For switching windows/tabs or switching into an iframe.

How Thread.sleep () Works in Java

  • Thread.sleep () causes the current thread to debar performance for a specified period.
    Thread.sleep method throws InterruptedException when interrupted.
    It can be care by the throws method or try match cube.

Limitations of Using Thread.sleep ()

  • It can slack down trial rooms when overuse.
    Tests may still miscarry if loading is slower than expected.

This article explore when Thread.sleep () is needed, how it works in Java, and its limitations.

Why do you need look dictation in Selenium?

Most modern web applications are built using Ajax and JavaScript and are based on popular frameworks such as. These technologies take a certain time to load elements when the page is loaded for the first clip or refreshed.

While using and trying to locate web elements in such applications using, it can not encounter the constituent as the event happen in a fraction of a second, and hence it throwsNoSuchElementException.

This might be quite surprising since you can easily see the element present on the DOM while inspect the page. This is one of the unpredictable behaviours, which needs to be handled by applying proper wait commands.

Providing proper script is rattling crucial as they make the scripts more reliable, thereby ensuring automation yields accurate results.

Read More: ​​

Types of Selenium Wait Commands

Implicit wait:This is used to tell the WebDriver to await for a certain amount of time before it drop a “NoSuchElementException”. This wait is use globally, which means that the same wait mechanism will work for all the factor in the afford code.

driver.manage () .timeouts () .implicitlyWait (20, TimeUnit.SECONDS);

In the above example, if the ingredient is not located on the webpage within 20 sec, it will throw an exception automatically.

  • Explicit delay: This is used to recite the WebDriver to wait for certain expected weather or maximal time exceeded before throwing an “ElementNotVisibleException” exception. It is an intelligent variety ofwaitbut can be utilise only for specified elements.
WebDriverWait wait=new WebDriverWait (driver, 20); wait.until (ExpectedConditions.visibilityOf (element));

In this example, Webdriver will expect explicitly for 20 secs for the element to be seeable, and if it is not visible, it will throw an exception.

Why and when to use Thread.sleep in Selenium?

Now, the question arises, if Selenium provides these two types of wait commands, why would an mechanisation tester opt for usingThread.sleep (). It would be interesting to cognise the role ofThread.sleep () command.

Below are some of the scenario whereThread.sleep ()comes to the rescue when none of the wait mechanisms works.

1. Testing active Web Elements

Many web applications have a carousel effectuation to display dynamic content. If you need to verify the profile of the following item in the merry-go-round, it is always well to useThread.sleep ()alternatively of Selenium waits as the carousel detail are very dynamically displayed.

Also Read:

2. Third-party testing

Nowadays, almost every web application has desegregation with third-party websites. Along with essay AUT (Application Under Test), you also need to validate that after clicking on any third-party connectedness, it navigates to the valid webpage, and the page charge properly.

Pro tip: Tools like SUSA can handle this autonomously — upload your app and get results without writing a single test script.

To assert this behaviour it is wise to useThread.sleep ()as it is real unpredictable to verify the shipment clip of any third-party site.

3. Switching Windows or Tabs

Clicking on some of the links on the webpage open them in a new browser window tab or a new browser representative. In such cases, to perform browser mechanisation tests, you need to switch the driver to the new browser window tab/ browser instance and perform action on it.

When you change and directly execute any mechanization case, it will dropNoSuchElementExceptionas the WebDriver has just switched and it is unable to locate the element. ApplyingThread.sleep ()after the switch command facilitate to work this.

4. Switching iFrame

Some web covering use iframe within the webpage. In such cases, to perform any action on the iframe elements, you first ask to switch to the iframe and then perform the required action on it.

When you switch and perform any automation case on the iframe web elements without applying any wait, Selenium will throw NoSuchElementException. Thread.sleep () can be applied after the iframe switch command to avoid the exception.

Read More:

Thread.Sleep in Selenium Java

While the above scenarios justify whyThread.sleep ()command in Selenium Java is significant. Let & # 8217; s understandThread.sleep ()function in detail using some point below:

  • As per the official definition from theOracle Java Documentation, Thread.sleep ()do the current thread to debar execution for a specified period.
  • Thread.sleep ()is not a Selenium wait, it is cater by Java.
  • It suspends the codification for the specified time and can be useful in debug the script under test.

Thread class is a class nowadays inJava.langpackage that is basically a thread of executing of the plan.

Thread class has two overloaded sleep methods,Thread.sleep (long millis) and Thread.sleep (long millis, int nanos).

  • Thread.sleep (long millis)

Thread.sleep (2000):Duration is in milliseconds for which thread will kip.

  • Thread.sleep (long millis, int nanos)

Thread.sleep (2000, 2000):The second argument is an additional clip in nanoseconds for which thread will sleep. It ranges from 0 to 999999.

  • Thread.sleep ()does not get a return case, and it return void.

Thread.sleepmethod throwInterruptedExceptionwhen any former thread interrupts the current ribbon and should be cover by the throws method or try catch block.

try {Thread.sleep (2000);} catch (InterruptedException e) {// TODO Auto-generated catch cube e.printStackTrace ();}

OR

public vacuum threadTest () throws InterruptedException {Thread.sleep (2000);}
  • It shed anIllegalArgumentExceptionwhen sleep time is negative.
Thread.sleep (-2000;)
  • Both the sleep() methods of Thread class are static methods. Hence, they should be accessed in a static way by using class name.
Thread.sleep (2000);

Now that it is discussed, why and how to useThread.sleep ()in the Selenium test, let ’ s see an representative demonstrating the same.

In the instance, use theMakeMyTrip website,which will occupy some time to lade after snap on the “ Hotels ” tab. And when Selenium tries to locate and click on the Search push on the “ Hotels ” page, it will castNoSuchElementExceptionas the element was not loaded before clicking on it.

Example 1: Testing Dynamic Web Elements

public class ThreadSleep {static WebDriver driver; static String url = `` https: //www.makemytrip.com/ ''; @ BeforeClass public static void setUp () {WebDriverManager.chromedriver () .setup (); driver = new ChromeDriver (); driver.manage () .window () .maximize (); //Launch MakeMyTrip website driver.get (url);} @ Test public void search () throws InterruptedException {//Click on Hotels tab driver.findElement (By.cssSelector (`` li.menu_Hotels '')) .click (); //Click on Search button driver.findElement (By.cssSelector (`` button # hsw_search_button '')) .click (); List & lt; WebElement & gt; hotel = driver.findElements (By.xpath (`` //span [contains (@ id, 'htl_id_seo_ ')] '')); //Click on the inaugural hunt issue hotels.get (0) .click ();} @ AfterClass public void tearDown () {driver.quit ();}}

Run the above program and mention that Selenium will throwNoSuchElementExceptionat line 34.

Add Thread.sleep (2000)after line 33 and run the program again. This time the program will pass as the thread got paused for 2 s, and the Search web element was loaded before clicking on it.

Talk to an Expert

Example 2: Third-Party Testing

In this model, on the MakeMyTrip home page, pawl on the facebook link from footer links and verify that it is redirecting to the MakeMyTrip facebook page.

public class ThreadSleep {still WebDriver driver; unchanging String url = `` https: //www.makemytrip.com/ ''; @ BeforeClass public unchanging void apparatus () {WebDriverManager.chromedriver () .setup (); driver = new ChromeDriver (); driver.manage () .window () .maximize (); // Launch MakeMyTrip website driver.get (url);} @ Test public emptiness facebookClick () throws InterruptedException {JavascriptExecutor js = (JavascriptExecutor) driver; WebElement wb = driver.findElement (By.xpath (`` //a [contains (@ href, 'facebook ')] /span '')); js.executeScript (`` argumentation [0] .click (); '', wb); Assert.assertEquals (driver.getCurrentUrl (), `` https: //www.facebook.com/makemytrip/ '');} @ AfterClass public void tearDown () {driver.quit ();}

Run the above program and note that Selenium throwsAssertionErrorsince the expected page was [https: //www.facebook.com/makemytrip/] but Selenium found [https: //www.makemytrip.com/]

This pass as Selenium could not wait for the redirected page to load altogether and returns the late page url instead of the redirected url. Hence, usingThread.sleep ()gives the redirected page a time window of few seconds to lade completely, before returning the page URL.

Read More:

Limitations of Thread.sleep

Using Thread.sleep ()frequently in an automation model is not a full practice. If the applied sleep is of 5 secs and the web element is displayed in 2 secs only, the excess 3 secs will increase the execution time. And if you use it more often in the model, the execution time would increase drastically.

You always have to guess and applyThread.sleep ()seconds in advance, as there is no guarantee that the web element would be ascertainable under that specified time.

On a closure billet

However, as discussed in this clause, when none of the Selenium wait commands work to locate the web element,Thread.sleep ()can be apply to avoid unnecessary failure in the automation script.

Just as Thread.sleep ()avoids flaky exam and mistaken positive, scarper Selenium Tests on will help improve the overall accuracy of the trial. By using like BrowserStack Automate, you can accession 3000+ existent devices and browser combinations to test under.

Moreover, you can speed up your crisscross browser compatibility tests by running them on different browsers simultaneously using. This way, Selenium Testing get a lot easier and assist deliver a high-quality user experience.

Tags
54,000+ Views

# Ask-and-Contributeabout this topic with our Discord community.

Related Guides

Automate This With SUSA

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.

Try SUSA Free

Test Your App Autonomously

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.

Try SUSA Free