Next-Gen App & Browser Testing Cloud
Trusted by 2 Mn+ QAs & Devs to accelerate their release cycles

Learn how to use Python sleep() function with time.sleep() for delays, pauses, and timing in your code with real-world examples.
January 13, 2026
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.
In Python, sleep() is a function from the time module that pauses the execution of your code for a specified amount of time.
Steps to Use Python sleep()
Use Cases of 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")
To pause code execution in Python, you can use the time.sleep() function. First, you need to import sleep from the time 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>
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() 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!
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.
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)")

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)
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()
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.")
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()
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()
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))
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!")
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.
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.
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.
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.
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.
Author
Did you find this page helpful?
More Related Hubs
TestMu AI forEnterprise
Get access to solutions built on Enterprise
grade security, privacy, & compliance