Python sleep(): How to Use time.sleep() in Python

Idowu (Paul) Omisola

Posted On: August 15, 2025

15 Min

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

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

  • Import the time module to access the sleep() function.
  • Call time.sleep() with the number of seconds to pause, which can be an integer or a decimal for fractional seconds.

Use Cases of Python sleep() Function

  • Waiting for Dynamic Content to Load: Pauses execution to ensure web page elements or API-driven content fully load before interaction. Can use hard waits or conditional checks to reduce unnecessary delays.
  • System Resource Monitoring: Adds intervals between CPU or memory usage checks to prevent constant polling and reduce system load.
  • Simulating User Wait Times: Introduces random delays in automation scripts to mimic human behavior for web interactions.
  • Rate-Limited API Calls: Implements delays between requests to avoid exceeding API rate limits, often combined with exponential backoff.
  • Delaying Script Execution in Testing Frameworks: Provides controlled pauses in automated tests to ensure proper sequencing and timing.

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:

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:

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.

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.

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.

Info Note

Run your Selenium Python tests across 3000+ real browsers. Try LambdaTest 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.

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.

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:

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:

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.

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.

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.

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.

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.

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.

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.

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.

How LambdaTest SmartWait Help Overcome Wait Challenges?

LambdaTest 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:

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 LambdaTest SmartWait.

Watch the tutorial below by Anton Angelov to learn how to use LambdaTest 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.

Frequently Asked Questions (FAQs)

How to sleep in Python?

Use time.sleep(seconds) to pause execution. Import it with import time. Fractional seconds work for milliseconds. In async code, use await asyncio.sleep(seconds). Sleep is useful in loops, threads, or delaying tasks without freezing the entire program.

How to use sleep in Python?

Import time using import time. Call time.sleep(seconds) wherever a delay is needed. Fractional seconds like time.sleep(0.5) are allowed. Async code uses await asyncio.sleep(seconds) to pause tasks without blocking, useful for loops, threads, or scheduled tasks.

How to sleep Python code?

Use import time and call time.sleep(seconds) to pause a program. Fractional seconds work for milliseconds. Async functions use await asyncio.sleep(seconds) to delay without blocking. Sleep is useful for pacing loops, waiting, or scheduling actions without freezing program execution.

How to add sleep in Python?

Add time.sleep(seconds) in code to create delays. Import time. Fractional seconds allow precise timing. Async code uses await asyncio.sleep(seconds) for non-blocking pauses. Sleep helps in loops, threads, or scheduled tasks, making execution timing more controllable and predictable.

How to use sleep Python?

Import the time module and call time.sleep(seconds) for execution pauses. Fractional seconds allow precise timing. Async code uses await asyncio.sleep(seconds) for non-blocking delays. Sleep is useful for throttling loops, timing events, or delaying tasks in threads.

How to import sleep in Python?

Use import time and call time.sleep(seconds) or from time import sleep and call sleep(seconds). Async code uses await asyncio.sleep(seconds) after importing asyncio. Sleep works in loops, threads, and scheduled operations to control execution timing.

What is sleep in Python?

Python’s sleep function pauses execution for a set number of seconds. Import via import time and call time.sleep(seconds). Fractional seconds allow millisecond delays. Async code uses await asyncio.sleep(seconds) for non-blocking pauses in asynchronous tasks.

How to make Python sleep for 1 second?

Import time and call time.sleep(1) to pause for one second. Async code uses await asyncio.sleep(1) for non-blocking delays. Sleep is practical in loops, threads, or delayed operations, letting programs pause temporarily without freezing other tasks.

How to make Python sleep milliseconds?

Python supports fractional seconds with time.sleep(). Example: time.sleep(0.001) pauses one millisecond. Async code uses await asyncio.sleep(0.001) for non-blocking delays. Sleep helps control timing, pacing loops, or delaying tasks precisely.

How to make Python sleep 10 seconds?

Call time.sleep(10) to pause execution for ten seconds. Import time first. Async code uses await asyncio.sleep(10) to pause tasks without blocking others. Sleep works in loops, threads, or scheduled operations for controlled timing.

How to use Python thread sleep?

Threads can pause using time.sleep(seconds) without affecting other threads. Import time and call it inside a thread. Async threads use await asyncio.sleep(seconds) for non-blocking delays. Sleep is useful for pacing threads or preventing CPU overuse.

How to make Python sleep 5 seconds?

Import time and call time.sleep(5) to pause for five seconds. Async code uses await asyncio.sleep(5) for non-blocking delays. Sleep helps delay execution, pace loops, or schedule events in scripts

Citations

Author

Idowu is a self-taught programmer, coding YouTuber, and technical writer with a penchant for teaching. He started his coding career in 2018 but combined it with technical writing a year later and has never looked back. He has worked for a couple of websites over the years, and you'll find some of his coding guides on popular websites like MUO. He loves discussing software structure and coding topics in Python, JavaScript, Golang, and TypeScript. And when it comes to software testing, he's a fan of Playwright and Selenium.

Blogs: 7

linkedintwitter