To create a time delay (pause) in Python, use the time.sleep()
function from the time
module. This is the standard method for adding delays in most scripts. Below are detailed explanations and examples:
1. Basic Delay with time.sleep()
The simplest way to introduce a delay:
import time
# Delay for 3 seconds
time.sleep(3)
# Delay for 0.5 seconds (500 milliseconds)
time.sleep(0.5)
Notes:
- The argument is in seconds (can be an integer or float).
- The delay is approximate due to system scheduling.
2. Delays in Loops
Use delays to space out iterations:
import time
for i in range(5):
print(f"Count: {i+1}")
time.sleep(1) # Wait 1 second between iterations
3. Async Delays with asyncio.sleep()
For asynchronous code (e.g., using async
/await
), use asyncio.sleep()
to avoid blocking the event loop:
import asyncio
async def main():
print("Starting...")
await asyncio.sleep(2) # Non-blocking delay
print("...2 seconds later")
asyncio.run(main())
4. Delays in Threading
Use delays in multithreaded applications without blocking the main thread:
import threading
import time
def background_task():
print("Task started")
time.sleep(5) # Delay in a background thread
print("Task completed")
thread = threading.Thread(target=background_task)
thread.start()
print("Main thread continues running")
5. GUI Applications (Tkinter)
Avoid freezing GUIs by using after()
instead of time.sleep()
:
import tkinter as tk
def delayed_action():
print("This runs after 2 seconds")
root = tk.Tk()
root.after(2000, delayed_action) # Delay in milliseconds (2000 ms = 2 sec)
root.mainloop()
6. Precision Delays (Advanced)
For high-precision delays (e.g., in simulations), use time.perf_counter()
:
import time
def precise_delay(duration):
start = time.perf_counter()
while time.perf_counter() - start < duration:
pass # Busy-wait (not recommended for long durations)
precise_delay(0.001) # ~1 millisecond delay (uses CPU)
Common Use Cases
- Rate Limiting: Slow down API requests.
for _ in range(10):
make_api_request()
time.sleep(1) # Wait 1 second between requests
- User Feedback:
print("Processing...")
time.sleep(2)
print("Done!")
- Animation/Effects:
import sys
for char in "Loading...":
sys.stdout.write(char)
sys.stdout.flush()
time.sleep(0.1)
Key Considerations
- Blocking:
time.sleep()
blocks the current thread. Useasyncio
or threading for concurrency. - Negative Values: Passing a negative value to
sleep()
raises aValueError
. - GUI/Event Loops: Use framework-specific methods (e.g.,
after()
in Tkinter,QTimer
in PyQt).
Choose the method based on your application type (script, async, GUI, etc.). For most cases, time.sleep()
is sufficient!