How to Wait in Python: Python Wait Tutorial With Examples

Ini Arthur

Posted On: August 14, 2025

15 Min

Using Python wait help you ensure the code wait for necessary elements to load before interacting with them. This mimics real user behavior and avoid common issues like attempting to click a button that hasn’t appeared yet or filling out a form that’s not fully loaded.

Overview

In Python, waits refer to mechanisms that pause the program’s execution until a certain condition is met or a specific amount of time has passed.

Methods for Using Python Waits

  • time.sleep(): Pauses program execution for a fixed number of seconds, blocking the current thread.
  • threading.Event().wait(): Makes a thread wait until another thread signals an event, useful for synchronization.
  • asyncio.sleep(): Suspends an asynchronous coroutine without blocking the event loop, allowing other tasks to run.
  • Custom Wait Functions With Polling: Repeatedly check a condition at intervals, enabling flexible waits but potentially consuming CPU.
  • time.perf_counter(): Provides a high-resolution timer for measuring elapsed time with precise accuracy.

What Are Python Waits?

Waits in Python comprise the different methods and functions used to halt an ongoing thread for some time. The wait() function is not built-in as implemented in another programming language. However, it is found in the time module and threading library.

Python wait can be achieved for a specified number of seconds by using the sleep() function of the time module. The Event class in the threading library has a wait() method that pauses the execution of a thread until an event object’s flag is set and the paused thread continues code execution.

Besides, Python waits can also be implemented in automation testing with tools like Selenium.

Methods to Implement Waits in Python

Waiting in Python can range from adding simple pauses to coordinating multiple threads or asynchronous tasks. The right approach depends on whether you need a fixed delay, synchronization, or precise control over timing.

time.sleep() for Simple Delays

time.sleep(seconds) pauses execution for a specified number of seconds. It is commonly used for simulating delays, pacing output, or avoiding rate limits in scripts. However, it blocks the entire thread.

Example:

threading.Event().wait() for Thread Synchronization

threading.Event().wait(timeout) allows threads to pause until a specific event is set or a timeout occurs. This enables coordination between threads without busy-waiting.

Example:

asyncio.sleep() in Asynchronous Programming

asyncio.sleep(seconds) pauses inside an asynchronous function without blocking the event loop. This makes it ideal for code using the Python asyncio library.

Example:

Custom Wait Functions with Polling

Polling repeatedly checks a condition until it becomes true or a timeout occurs.

Example:

time.perf_counter() for High-Resolution Timing

time.perf_counter() provides precise timing for performance measurement.

Example:

Info Note

Run your Selenium Python tests across 3000+ real browsers. Try LambdaTest Today!

Methods to Implement Waits in Python With Selenium

Selenium waits help your script handle dynamic content and avoid errors from interacting with elements that are not yet ready. By using implicit, explicit, or fluent waits in Selenium Python, you can control timing more effectively and ensure smoother execution.

Implicit Waits for Setting Global Timeouts

Implicit waits tell Selenium to keep trying to find an element for a set amount of time before throwing an exception. You set them once and they apply globally to all element searches in the WebDriver instance.

Example:

If the element appears earlier than the timeout, Selenium proceeds immediately, so your script doesn’t always pause for the full duration.

While implicit waits are easy to implement, they apply to all elements and can sometimes mask slow-loading elements that should be handled more precisely.

Explicit Waits for Specific Conditions

Explicit waits give you targeted control over how long Selenium waits for a specific event or condition. They work with Selenium WebDriverWait and ExpectedConditions in Selenium to monitor for things like element visibility, clickability, or the presence of text.

Example:

With explicit waits, you avoid unnecessary delays because Selenium checks the condition periodically and moves on as soon as it is met.

This is more efficient and reliable for dynamic pages compared to implicit waits.

Fluent Waits for Customizing Polling Intervals

Fluent waits are essentially explicit waits with extra flexibility. They let you define not only the maximum timeout but also the frequency of checks and the types of exceptions to ignore during polling.

Example:

In this case, Selenium checks for the element every 2 seconds for up to 15 seconds.

Fluent waits are helpful when you know an element might take time to appear and want to avoid constant high-frequency polling that could impact performance.

How to Implement Waits in Python?

Let’s look at how to use Python waits with tools like Selenium. To run tests, we will use the online Selenium Grid offered by LambdaTest. This will help achieve much-needed scalability and reliability.

To get started, check out this documentation on Selenium Python testing with LambdaTest.

Test Scenario:

  1. Navigate to the homepage of the LambdaTest eCommerce Playground website.
  2. Wait for the homepage to load completely.
  3. Check for the presence of page elements.
  4. Raise an assertion that page elements are complete.

Prerequisites

  1. Get the LambdaTest Username and Access Key. Go to Account Settings, then click on Password & Security.
  2. Create a conftest.py file for your pytest fixture.
  3. This driver fixture creates a Remote WebDriver session on LambdaTest using credentials and capabilities pulled from environment variables, yields it to the test, and integrates with pytest_runtest_makereport to track test phases. After execution, it marks the test as passed or failed in LambdaTest and quits the browser.

    Based on your testing requirements, you can also generate capabilities from the LambdaTest Automation Capabilities Generator.

Implementation

  1. Create a pages_sleep_wait.py file. This is your Page Object for implementing wait using time.sleep() function.
  2. Import all the modules needed to create the test case.
  3. Create the test_sleep_wait() method decorated with @pytest.mark.usefixtures(“driver”). This decorator invokes the fixture “driver” to be used by pytest before executing the test function.
  4. Use the time.sleep() method to wait 5 seconds for the page to load completely.
  5. Get the number of elements using the elements_count.get_elements_count() method and save it to the variable count. Raise an assert statement to validate the expected number of elements equals the value of the count variable.

Test Execution

Run the test using the following command:

The LambdaTest Web Automation dashboard shows the status of our test execution.

LambdaTest Web Automation Dashboard

The 5 seconds of sleep time used in our script means that even when elements on the page are available, the driver will still wait for the time to be exhausted. This can only prolong the wait time than it’s necessary.

Watch the tutorial below by Anton Angelov to learn how to use waits in Selenium 4.

Anton is a widely recognized leader in the global QA community, serving as Managing Director, Co-Founder, and Chief Test Automation Architect at Automate The Planet, a leading consulting firm specializing in test automation strategy, implementation, and enablement.

How LambdaTest SmartWait Simplifies Python Test Automation?

LambdaTest SmartWait is the simplest way to manage waits in your Selenium Python scripts when running on the LambdaTest cloud grid. Instead of manually writing explicit waits for every element, SmartWait uses an intelligent algorithm to pause execution until all conditions are met or the specified time expires.

By default, it improves test reliability while reducing flaky failures caused by dynamic load times.

Test Scenario:

  1. Navigate to the homepage of the LambdaTest eCommerce Playground website.
  2. Click on Blog on the navigation menu.
  3. Click on the first blog post.
  4. Raise an assertion that the page title is correct.

Implementation

  1. Create a test_smartwait.py file. It is a page object that uses SmartWait implicitly from the grid. No explicit waits needed.

  2. Create a capabilities option dictionary or use the Automation Capabilities Generator.

  3. Replace the previous options argument of the set_capability() method (i.e., in the conftest.py file) with the one with the smartWait key-value pair.
  4. Call the smartwait.click_blog_link() method to click on the blog section link.
  5. Use the smartwait.click_first_post() method to click on the first blog post.
  6. Use the assert statement to confirm that the words amet volutpat are in the page title.

Test Execution

Run the test using the following command:

The LambdaTest Web Automation Dashboard shows the status of our test execution.

The LambdaTest Web Automation Dashboard shows the status of our test execution.

You can check out this another video by Anton Angelov where he showcases how to use LambdaTest SmartWait for Selenium test automation.

Best Practices for Implementing Waits in Python

Using waits correctly ensures your Python code runs efficiently and reliably. Following best practices prevents unnecessary delays and errors during execution.

  • Avoid Overusing time.sleep(): The time.sleep() function blocks execution, slowing your code unnecessarily. Use it sparingly for fixed pauses and debugging, not for dynamic waits.
  • Choose the Right Wait Strategy: Pick waits based on task needs: time.sleep() for fixed delays, threading.Event().wait() for threads, asyncio.sleep() for async, and explicit waits for conditions.
  • Handle Timeouts and Exceptions: Always set timeouts to prevent indefinite waits. Wrap waits in try-except blocks and add retries or fallback actions for robust code.
  • Avoid Busy-Wait Loops: Constantly checking conditions wastes CPU resources. Prefer event-driven or condition-based waits to conserve processing power.
  • Log Waiting Events: Track wait times and triggers through logging. This helps identify bottlenecks and optimize performance.

Troubleshooting Common Issues with Waits

Implementing waits can still lead to errors if conditions or timing aren’t handled correctly. Knowing common issues helps prevent failures and improve script reliability.

  • Timeout Errors: Timeouts occur when waits are too short or conditions are incorrect. Verify logic, adjust durations, and implement incremental retries to reduce failures.
  • StaleElementReferenceException in Selenium: Elements may detach from the DOM before interaction. Re-locate elements, use explicit waits, and retry actions to maintain reliability.
  • Network Latency Considerations: Slow connections can cause unexpected delays. Increase wait durations or use adaptive waits to handle variability.
  • Resource Contention: Multiple threads or processes may delay expected conditions. Ensure proper synchronization and avoid unnecessary blocking.
  • Condition Misconfiguration: Incorrectly defined wait conditions cause failures. Review and test conditions to ensure they accurately reflect the target state.

Conclusion

There are several reasons why Python wait mechanisms have been used. Some of these reasons include collecting user input, waiting for server responses, fetching web page resources, etc.

Like other programming languages, Python waits can be used with tools like Selenium for web automation. It offers several ways to apply Python waits in test automation scripts.

Frequently Asked Questions (FAQs)

How to wait in Python?

The simplest method is using the time module. First, import it with import time. Then call time.sleep(seconds) to pause execution for the desired number of seconds. You can use integers or floats, such as time.sleep(2) to wait exactly two seconds before continuing the program.

How to make Python wait?

Python’s built-in time.sleep() function is the most common solution. Start by importing the time module. Pass the delay in seconds, for example time.sleep(5), to pause execution. You can also use fractional seconds like 0.5 for half a second, which is helpful for smoother timing control.

How to make a wait in Python?

Waiting in Python is easy with the time module. Import it using import time. Then use time.sleep(seconds) where seconds can be an integer or float. For instance, time.sleep(0.5) creates a half-second pause, making it useful for animations, delays, or pacing code execution predictably.

How to make Python wait 1 second?

Import the time module and use time.sleep(1). This pauses the program for exactly one second before resuming. The same function works for longer or shorter delays by changing the value. It’s a simple, built-in way to control timing without needing extra libraries or complex code.

What is wait() in Python?

Python itself does not have a built-in wait() function for timing. Waiting is usually done with time.sleep(seconds) from the time module. However, some libraries like threading or asyncio define their own wait() methods for synchronization or event handling, which are different from a simple pause.

What is 0.2 seconds sleep in Python?

time.sleep(0.2) pauses the program for 0.2 seconds, which is 200 milliseconds. The time.sleep() function accepts float values for precise control over short delays. This is useful for animations, smooth loops, or preventing rapid execution that could overwhelm external resources or make the output unreadable.

How to ask Python to wait?

Import the time module with import time and call time.sleep(seconds). Replace seconds with the amount of time to pause. For example, time.sleep(3) stops execution for three seconds. This method is built-in, works with floats, and is widely used for timing and pacing code.

What is delay() in Python?

Python does not have a native delay() function. Instead, you can use time.sleep(seconds) to create pauses. For example: import time; time.sleep(2) waits for two seconds. Some specialized libraries may implement their own delay() functions, but for most scripts, time.sleep() is the standard method for creating delays.

Citations

Author

Iniubong Arthur is a dedicated individual with strong critical thinking, design thinking, and software engineering skills. His current focus is on developing software solutions in Django, Flutter & React that solves real-world problems.

Blogs: 4

linkedintwitter