Power Your Software Testing with AI Agents and Cloud
The Native AI-Agentic Cloud Platform to Supercharge Quality Engineering. Test Intelligently and Ship Faster.
- TestMu AI (Formerly LambdaTest)
- /
- Blog
- /
- Python sleep(): How to Use time.sleep() in Python
Python sleep(): How to Use time.sleep() in Python
Learn how to use Python sleep() function with time.sleep() for delays, pauses, and timing in your code with real-world examples.
Last Updated on:
On This Page
- What Is Python sleep() Function?
- How to Use time.sleep() in Python?
- Common Use Cases of Python time.sleep()
- Best Practices for Using time.sleep() in Python
- Common Errors When Using time.sleep() and Troubleshooting
- AI Coding Assistants and time.sleep()
- How TestMu AI SmartWait Help Overcome Wait Challenges?
The Python sleep() function pauses code execution for a specified duration. It is useful for managing timing, simulating real-world delays, and controlling the flow of automation scripts. By pausing code execution at precise intervals, Python sleep() function helps manage task execution and avoids overloading system resources.
Overview
To pause code execution in Python, import the time module and call time.sleep() with the desired number of seconds. Use time.sleep() for simple, synchronous delays, or use asyncio.sleep() for non-blocking, concurrent delays in single-threaded asynchronous programs.
Steps to Use Python sleep()
- Importing the module: To use the Python sleep function, you must first import the time module to gain access to the time.sleep() function in your script.
- Calling the function: Call the time.sleep() function with an integer or decimal argument to pause code execution for a specified number of seconds or fractional seconds.
Use Cases of Python sleep() Function
- Waiting for dynamic content: Use the time.sleep() function to pause execution, ensuring that dynamic web page elements or API-driven content fully load before your script interacts with them.
- System resource monitoring: Use the time.sleep() function to add intervals between CPU or memory usage checks, which prevents constant polling and reduces overall system load.
- Simulating user wait times: Introduce random delays using the time.sleep() function in automation scripts to mimic human behavior during web interactions.
- Rate-limiting API calls: Implement delays between requests using the time.sleep() function to avoid exceeding API rate limits and prevent your script from being blocked.
- Delaying script execution in testing: Provide controlled pauses using the time.sleep() function in automated testing frameworks to ensure proper sequencing and timing of asynchronous elements.
Alternative Wait Solutions
- Asynchronous delays: Use the asyncio.sleep() function to create non-blocking delays in single-threaded Python programs, allowing other tasks to run concurrently and reducing memory usage.
- Automated testing: Use TestMu AI SmartWait to intelligently pause test execution until specific conditions are met or a timeout expires, reducing flaky test failures.
- Task scheduling: Use dedicated tools like Celery or APScheduler instead of the time.sleep() function for scheduling tasks in production environments.
What Is Python sleep() Function?
The Python sleep() function is a built-in way to pause the execution of your code for a specified number of seconds. It is often used to simulate delays, control timing, or wait between operations in loops and scripts.
In Python, the sleep function is part of the time module, which means you use it as time.sleep(). This allows you to specify exactly how long your code should wait before continuing. Using time.sleep() is the standard approach to implement Python waits in the code.
Example:
from time import sleep
print("Start")
sleep(3) # pauses execution for 3 seconds
print("End after 3 seconds")
How to Use time.sleep() in Python?
To pause code execution in Python, you can use the time.sleep() function. First, you need to import sleep from the time module.
Importing Python sleep Module
Here’s how to import the time.sleep() function so you can use it in your code:
from time import sleep
Basic Usage Example:
This example prints “Hello world” immediately, waits for 4 seconds, and then prints the next statement. It demonstrates a simple single-threaded delay.
# import the sleep function from the time module
from time import sleep
print("Hello world")
# pause code execution for 4 seconds
sleep(4)
# this line executes after 4 seconds
print("Another hello world") </em>
Using time.sleep() in Multi-Threading
In a multi-threaded code, time.sleep() only blocks the thread it is called in. Other threads continue running independently.
import threading
from time import sleep, time
def sleeper(name, delay):
sleep(delay)
print(f"[{name}] Woke up after {delay} seconds")
threads = [
threading.Thread(target=sleeper, args=(f"Thread-{i+1}", d))
for i, d in enumerate([5, 3, 4, 2])
]
start_time = time()
for t in threads:
t.start()
print(f"Main thread is free to do other work. 5 + 6 is {5+6}")
# Wait for threads to finish, if needed
for t in threads:
t.join()
print(f"All threads finished in {time() - start_time:.2f} seconds")</em>
Using asyncio.sleep() for Efficient Delays
Using asyncio.sleep() allows non-blocking delays in a single-threaded program. This reduces memory usage while letting tasks run concurrently.
import asyncio
from time import time
async def sleeper(name, delay):
await asyncio.sleep(delay)
print(f"[{name}] Woke up after {delay} seconds")
async def main():
start_time = time()
tasks = [
asyncio.create_task(sleeper(f"Task-{i+1}", d))
for i, d in enumerate([5, 3, 4, 2])
]
print(f"Main coroutine is free to do other work. 5 + 6 is {5+6}")
# Wait for all tasks to finish
await asyncio.gather(*tasks)
print(f"All tasks finished in {time() - start_time:.2f} seconds")
# Run the main coroutine
asyncio.run(main())</em>
Note: Run your Selenium Python tests across 3000+ real browsers. Try TestMu AI Today!
Common Use Cases of Python time.sleep()
time.sleep() is a simple yet powerful function in Python that allows you to pause execution for a specified number of seconds. It is widely used in automation, automated testing, monitoring, and simulations to handle timing-related requirements.
Waiting for Dynamic Content to Load
For tasks like Python web scraping, content is loaded dynamically using JavaScript or APIs. Pausing execution ensures that all elements are fully loaded before the program interacts with them, preventing errors or incomplete data retrieval.
import random
import time
# Simulate dynamic content that loads randomly between 1-4 seconds
def content_ready():
return time.time() - start_time >= load_time
# Hard wait with time.sleep()
print("HARD WAIT")
start_time = time.time()
load_time = random.uniform(1, 4)
print("Waiting 5 seconds for content...")
# Always waits 5 seconds
time.sleep(5)
print(f"Content loaded! (It took {load_time:.1f}s)")
Here, a hard wait pauses execution regardless of actual content load time. Conditional waiting, in contrast, can reduce unnecessary delays by checking if the content is ready.
import random
import time
def content_ready():
return time.time() - start_time >= load_time
# Conditional wait
print("CONDITIONAL WAIT")
start_time = time.time()
load_time = random.uniform(1, 4)
print("Waiting for content to load...")
while not content_ready():
time.sleep(0.5)
actual_wait = time.time() - start_time
print(f"Content loaded! (Waited {actual_wait:.1f}s)")

System Resource Monitoring
Monitoring CPU, memory, or other system resources often requires periodic checks. Using time.sleep() allows the program to take readings at intervals, avoiding constant polling that could itself burden the system.
The following example measures the system’s global memory usage for 5 seconds:
import time
import psutil
for i in range(5):
cpu_percent = psutil.cpu_percent()
print(f"CPU Usage: {cpu_percent}%")
time.sleep(5)
As mentioned earlier, you can also use time.sleep() function to monitor a specific application’s memory usage over time.
The following example reports the calculation’s memory usage every 2 seconds:
import time
import psutil
import os
pid = os.getpid()
process = psutil.Process(pid)
a = 4 + 8
print(a)
memory_info = process.memory_info()
memory_mb = memory_info.rss / 1024 / 1024
print(f"Memory after calculation: {memory_mb:.2f} MB")
for i in range(5):
memory_info = process.memory_info()
memory_mb = memory_info.rss / 1024 / 1024
print(f"Memory Usage: {memory_mb:.2f} MB")
time.sleep(2)
Simulating User Wait Times
Automation scripts often need to mimic human behavior to interact with web pages correctly. Introducing pauses with time.sleep() helps simulate real user wait times, ensuring that elements are ready for interaction.
In the following example, there is an exponential delay between a maximum of 5 retries for a failed request.
import time
import random
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.get("https://ecommerce-playground.lambdatest.io/index.php?route=common/home")
time.sleep(random.uniform(3, 6))
next_button = driver.find_element(By.CLASS_NAME, "carousel-control-next-icon")
driver.execute_script(
"arguments[0].scrollIntoView({ behavior: 'smooth', block: 'center' });",
next_button,
)
time.sleep(random.uniform(3, 7))
next_button.click()
time.sleep(random.uniform(4, 8))
driver.quit()
Simulating Delays in Rate-Limited API Calls
Many APIs limit how quickly you can make requests. Introducing delays between requests prevents exceeding limits and getting blocked. time.sleep() is an easy way to implement these pauses, and exponential backoff can help in retries.
Here’s an example that applies a random wait time before the next action.
import requests
import time
url = "https://ecommerce-playground.lambdatest.io/index.php?route=common/home"
max_retries = 5
backoff = 1
for attempt in range(1, max_retries + 1):
try:
print(f"Attempt {attempt}...")
response = requests.get(url, timeout=5)
if response.status_code == 200:
print("Request successful!")
break
else:
print(f"Failed with status: {response.status_code}")
raise Exception("Non-200 status")
except Exception as e:
print(f"Error: {e}")
if attempt < max_retries:
wait_time = backoff * (2 ** (attempt - 1))
print(f"Retrying in {wait_time} seconds...
")
time.sleep(wait_time)
else:
print("Max retries reached. Giving up.")
Debugging and Observing Test Behavior
During development or automated testing, pausing execution lets you observe states, UI changes, or log outputs. This can make debugging easier and more intuitive.
The following code waits after each action to observe the effect.
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
driver = webdriver.Chrome()
driver.get("https://ecommerce-playground.lambdatest.io/index.php?route=common/home")
time.sleep(10)
first_featured = driver.find_element(By.XPATH, "//h3[text()='Featured']")
first_featured.click()
time.sleep(5)
next_button = driver.find_element(By.CLASS_NAME, "swiper-button-next")
next_button.click()
time.sleep(10)
driver.quit()
Delaying Between Steps in Slow Applications
Some applications respond slowly or have heavy processing steps. Introducing deliberate pauses ensures that actions do not overlap and that each step completes successfully.
For instance, the following code waits 10 seconds after loading the website and waits another 6 seconds after clicking a navigation button to capture the next page title.
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
driver = webdriver.Chrome()
driver.get("https://ecommerce-playground.lambdatest.io/index.php?route=common/home")
time.sleep(10)
page_button = driver.find_elements(By.ID, "mz-product-listing-image-39217984-0-1")
assert len(page_button[0]) > 0, "Button not found on the page"
page_button[0].click()
time.sleep(6)
print(driver.title)
driver.quit()
Simulating Real-Time Data Processing
In simulations or real-time processing applications, introducing delays between operations can help mimic the natural time gap between events, making the simulation more realistic.
For example, the following code simulates delays between temperature data streams by using the time.sleep() function.
import time
import random
for i in range(10):
temp = round(random.uniform(20.0, 30.0), 2)
print(f"Reading {i + 1}: {temp}°C")
time.sleep(random.uniform(1.5, 4))
Waiting for External Resources or Conditions
Sometimes scripts need to wait for external resources, like a file being created or a server becoming available. Using time.sleep() in a loop can check for these conditions periodically without overloading the system.
The code below simulates a 30-second timeout to wait for a file to be created. Once created, it can then take further action on the file.
import os
import time
file_path = "output.csv"
timeout = 30
start_time = time.time()
while not os.path.exists(file_path):
if time.time() - start_time > timeout:
print("Timeout reached. File not found.")
break
print("Waiting for file to be created...")
time.sleep(2)
if os.path.exists(file_path):
print("File is now available!")
Delaying Script Execution in Testing Frameworks
While performing automation testing, you may often encounter popups or elements that appear asynchronously. Adding small delays with time.sleep() ensures that these elements can be detected and interacted with reliably.
The example below pauses execution to give time for a pop-up to appear. It then attempts to close the pop-up. If the pop-up doesn’t appear within the sleep delay, the try-except block ensures the test doesn’t fail and continues.
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
driver = webdriver.Chrome()
driver.get("https://example.com")
time.sleep(5)
try:
popup = driver.find_element(By.ID, "subscribe-popup")
popup_close = popup.find_element(By.CSS_SELECTOR, "[aria-label='Close']")
popup_close.click()
print("Popup closed.")
except Exception:
print("Popup did not appear.")
driver.quit()
The above code serves as a simple fail-safe mechanism, temporarily stabilizing a flaky test caused by timing inconsistencies resulting from an asynchronous pop-up or delayed rendering.
Best Practices for Using time.sleep() in Python
Here are some best practices to keep in mind when using time.sleep() in Python. Following these can make your code more efficient, reliable, and easier to maintain.
- Use time.sleep() Only When Necessary: Avoid adding unnecessary delays that can slow down your program. Reserve time.sleep() for cases like simulating real-world waits or implementing rate limiting.
- Prefer Event-Based Waiting Over Fixed Delays: Waiting for specific events or conditions is more reliable than guessing with fixed sleep times. This approach makes your code faster and less prone to errors.
- Keep Sleep Durations as Short as Possible: Longer delays can accumulate and waste time, especially in loops or tests. Use the minimum duration needed for your scenario.
- Always Comment on Why time.sleep() is Needed: Documenting the reason for each time.sleep() helps others understand your intent. It also makes future improvements and debugging easier.
- Avoid Using time.sleep() for Scheduling in Production Code: For scheduling tasks, rely on standard tools like APScheduler, Celery, or external systems like CRON. For asynchronous scheduling in Python, consider using asyncio.sleep() with an asyncio event loop. These methods provide more control, reliability, and scalability than manually pausing execution.
- Be Mindful When Using time.sleep() Inside Loops: Repeated sleeps inside loops can consume memory, reduce performance, and slow down your program significantly.
- Monitor Tests With Sleeps for Flaky Behavior: Fixed delays can mask timing issues, making tests unreliable. Regularly review and replace them with event-based or condition-based pauses, such as explicit waits, whenever possible.
Common Errors When Using time.sleep() and Troubleshooting
While time.sleep() is a simple way to pause code execution, improper use can lead to unexpected behavior.
Here are some common errors and tips to troubleshoot them.
- Blocking of the Main Thread: Using time.sleep() directly in the main program flow pauses the entire program and prevents other code from running. To address this, you can use threading to synchronize waits across multiple threads. A more efficient approach is to use asyncio.sleep() function of Python asyncio library. It supports asynchronous single-threaded execution. For scheduled tasks, consider dedicated scheduling libraries like Celery, schedule, or AppScheduler.
- Endless Waits: Placing time.sleep() inside a loop without a proper exit condition can cause infinite delays. Use counters or timestamps to exit loops after a threshold, and avoid indefinite loops unless you are designing a polling mechanism with strong safeguards.
- Execution is Unnecessarily Slow: Arbitrary or excessive use of time.sleep() can accumulate delays and significantly increase runtime. Always use the shortest necessary wait or replace it with event-based waiting for better efficiency.
- Ignoring Failures Due to Race Conditions: Hard-coded sleep values can create race conditions if resources aren’t ready when the script proceeds, leading to abrupt failures. Avoid this by using explicit waits or condition-based synchronization to ensure resources are ready before continuing execution.
Do AI Coding Assistants Still Suggest time.sleep() in Test Scripts?
Yes. AI coding assistants such as GitHub Copilot and Cursor still autocomplete time.sleep() into Python test scripts, since older training data favors fixed waits over condition-based ones. The suggestion looks correct and runs without an error, so a developer often accepts it without checking whether a condition-based wait would work better.
Playwright's Python API takes a different approach. It auto-waits for an element to become visible, enabled, and stable before acting on it, polling the page state in short intervals instead of pausing for a fixed duration. Selenium's WebDriverWait works the same way, checking a condition repeatedly until it is true or a timeout is reached. Neither approach needs a hardcoded time.sleep() call to work.
The real limitation is that an AI assistant cannot tell which wait pattern a specific test needs just from the surrounding code. It has no way to know whether the page is slow, whether an element loads asynchronously, or whether a fixed delay will pass in CI but fail under different load. Treat every AI-suggested time.sleep() call in a test file as a prompt to ask for a condition-based alternative, not as a fix to accept as is.
How TestMu AI SmartWait Help Overcome Wait Challenges?
TestMu AI SmartWait makes managing waits in Python automation testing much easier. Instead of manually adding delays in your scripts, SmartWait intelligently pauses execution until all conditions are met or the specified timeout expires.
This method improves test reliability and minimizes flaky failures caused by dynamic load times, making your automated tests more stable and efficient.
Here’s an example configuration for using SmartWait in Python:
option_smartwait = {
"platform": "macOS Sonoma",
"version": "latest",
"name": "Python Test Automation",
"Build": "Python Wait Build",
"smartWait": 10, # Accepts integer values in seconds
"video": True,
"visual": False,
"network": True,
"console": True,
}
Here, the smartWait value, such as smartWait: 10, sets the maximum wait time in seconds, allowing tests to proceed as soon as the required conditions are satisfied.
To get started, you can check out this documentation on TestMu AI SmartWait.
Watch the tutorial below by Anton Angelov to learn how to use TestMu AI SmartWaits.
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.
Conclusion
You’ve learned how the Python sleep() function works, along with its key use cases, best practices, common errors and how to troubleshoot them. The sleep() function is a good way for controlling execution timing. It can help simulate delays, manage timing in tests, and coordinate task execution.
However, it’s important to use the Python time.sleep() function thoughtfully. For more efficient and reliable code, prefer event-based or condition-based waits whenever possible.
Citations
- time – Time access and conversions: https://docs.python.org/3/library/time.html
Author
Idowu Omisola is a technical writer and self-taught programmer with over 6 years of experience explaining software development and testing to developers. He is a Senior Technical Writer at ZenRows and has authored hundreds of articles across MakeUseOf, iGeeksBlog, ZenRows, and TestMu AI (formerly LambdaTest). On TestMu AI, he authored tutorials on Python load testing with Locust, Python unit testing with unittest, and pytest code coverage reports. He works with Python, JavaScript, and Go, and holds an MSc in Environmental Microbiology.
Reviewer
Shravan Mahajan is a Software Engineer at TestMu AI building Kane CLI, the command-line tool that runs browser automation from the terminal, describing flows in natural language that execute in a real Chrome browser and return pass or fail with shareable proof. He has an experience of 6 years in the Technical industry. His top skills are JavaScript, React.js, and full-stack development. At Fractal he built automated data pipelines with T-SQL, SSIS, Python, and Azure. He is also a Microsoft Certified Azure Data Engineer Associate.
Python Sleep FAQs
Did you find this page helpful?
More Related Blogs
TestMu AI forEnterprise
Get access to solutions built on Enterprise
grade security, privacy, & compliance
- Advanced access controls
- Advanced data retention rules
- Advanced Local Testing
- Premium Support options
- Early access to beta features
- Private Slack Channel
- Unlimited Manual Accessibility DevTools Tests






