The Tool Desk
Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Use time.sleep(seconds) to suspend the thread that calls it for a requested number of seconds. The argument can be an integer or a fraction, but the pause is a minimum: operating-system scheduling and system load can make execution resume later.
import time
print("Before")
time.sleep(2)
print("After")
What time.sleep() does
time.sleep() is a blocking, synchronous call. It suspends the calling thread; it does not automatically stop every thread in the process. In a single-threaded script, the whole program appears paused. In a multithreaded program, other threads can continue running while one thread sleeps.
The function returns None. Its purpose is the delay, not a result. Python documents the behavior and platform details at docs.python.org/3/library/time.html.
Syntax and imports
Explicit module import
import time
time.sleep(1)
This form makes it clear that sleep comes from Python’s time module.
Quick wins for a faster PC:
Clear out junk files and repair common Windows errorsFree Scan →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →#1 Best Overall
- Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
- Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
- Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
- Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
- 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
Import the function directly
from time import sleep
sleep(1)
The shorter form is valid, but an explicit time.sleep() call makes name collisions and the function’s origin easier to see.
Seconds, fractions, and conversions
The argument is measured in seconds. Floating-point values let you request fractional seconds, but they do not guarantee millisecond-accurate wake-ups.
| Desired delay | Expression |
|---|---|
| 1 second | time.sleep(1) |
| 500 milliseconds | time.sleep(0.5) |
| 100 milliseconds | time.sleep(0.1) |
| 10 milliseconds | time.sleep(0.01) |
| 1 millisecond | time.sleep(0.001) |
| 1 minute | time.sleep(60) |
For example:
import time
time.sleep(0.25) # request approximately one quarter of a second
time.sleep(1 / 1000) # request approximately one millisecond
Useful examples
Pause before continuing
import time
print("Starting...")
time.sleep(2)
print("Continuing...")
Countdown
import time
for remaining in range(3, 0, -1):
print(remaining)
time.sleep(1)
print("Go!")
Repeat work at a simple interval
import time
for number in range(5):
print(number)
time.sleep(1)
Each iteration prints, requests a one-second pause, and then continues.
Polling or processing items
import time
for item in items:
process(item)
time.sleep(0.2)
This is a fixed delay, not a complete rate limiter. Processing time, concurrency, bursts, and server responses may also need to be accounted for.
Rank #2
- 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
- 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
- Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
- 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
- What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
Why the pause can be longer than requested
time.sleep(1) asks Python not to resume the thread for about one second; it is not an exact timer or a hard real-time guarantee. The operating system may schedule the thread later, and interpreter overhead or system load can add time. Very small requests are especially sensitive to those effects. Current Python documentation describes different Unix and Windows timer implementations, but none changes the scheduling guarantee.
import time
start = time.perf_counter()
time.sleep(1)
elapsed = time.perf_counter() - start
print(f"{elapsed:.3f} seconds")
time.perf_counter() is intended for measuring elapsed durations and includes time spent sleeping. Use a monotonic clock rather than wall-clock time for elapsed-time decisions.
Loops without accumulating drift
Fixed-delay loop
import time
while True:
do_work()
time.sleep(10)
Here, the ten-second wait starts only after do_work() finishes. Starts can therefore be more than ten seconds apart, and the extra work time accumulates.
Deadline-based scheduling
import time
interval = 10
next_run = time.monotonic()
while True:
next_run += interval
do_work()
remaining = next_run - time.monotonic()
if remaining > 0:
time.sleep(remaining)
time.monotonic() is designed for comparing elapsed times and is not affected by system-clock corrections. See the Python monotonic-clock documentation.
Do these 3 things before closing this tab:
1Fix the driver behind crashes, sound loss and screen glitches2Repair Windows errors before they cause bigger problems3Scan for outdated or missing drivers - takes under a minuteRank #3
- Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
- Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
- Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
- Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
- What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
Threads: sleeping is not synchronization
One sleeping thread does not inherently pause its siblings:
import threading
import time
def worker():
for i in range(3):
print("Worker:", i)
time.sleep(1)
thread = threading.Thread(target=worker)
thread.start()
print("Main thread continues")
thread.join()
Do not insert an arbitrary sleep to guess that another thread has finished. A delay can be too short on a busy machine or unnecessarily long on an idle one. Use join(), an event, condition, queue, semaphore, or future to express the actual coordination requirement. Python’s threading guidance is at docs.python.org/3/faq/library.html#how-do-i-program-using-threads.
Wait that can be cancelled early
import threading
stop_event = threading.Event()
if not stop_event.wait(timeout=10):
print("Ten seconds elapsed")
else:
print("Stopped early")
Async code: use asyncio.sleep()
Calling time.sleep() in an async def function blocks the event loop, preventing other tasks from running:
import time
async def bad():
time.sleep(2) # blocks the event loop
Use the coroutine-based alternative:
import asyncio
async def main():
print("Before")
await asyncio.sleep(1)
print("After")
asyncio.run(main())
asyncio.sleep() suspends the current task and lets other tasks run. A zero delay is an optimized opportunity to yield to other tasks. Its current behavior, cancellation rules, and version-specific details are documented at docs.python.org/3.14/library/asyncio-task.html.
Rank #4
- Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
- Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
- Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
- Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
- Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
| Situation | Appropriate choice |
|---|---|
| Ordinary synchronous script | time.sleep() |
Code inside an async def coroutine |
await asyncio.sleep() |
| Wait for a thread or condition | Event, Condition, Queue, or a future |
| Run a callable later in a thread | threading.Timer or an executor |
| Limit an operation’s runtime | A timeout mechanism, not a preceding sleep |
| Retry a failure | Bounded retry with backoff and a maximum |
Delays between requests and retries
Simple pacing
import time
for url in urls:
response = fetch(url)
time.sleep(1)
Use the service’s documented limits and any client-library rate limiter when available. A fixed sleep alone does not account for response time or concurrent workers.
Bounded exponential backoff
import time
max_attempts = 5
base_delay = 1
for attempt in range(max_attempts):
try:
result = fetch_data()
break
except TemporaryError:
if attempt == max_attempts - 1:
raise
delay = base_delay * (2 ** attempt)
time.sleep(delay)
- Set a maximum attempt count and maximum delay.
- Retry only failures that are genuinely temporary.
- Add random jitter when many workers could retry together.
- Honor a server-provided retry instruction where applicable.
- Make shutdown and cancellation able to interrupt the wait.
Testing code that sleeps
Long real sleeps make unit tests slow and flaky. Inject the sleeping function so tests can record calls without waiting:
import time
def retry_operation(operation, sleep_fn=time.sleep):
for attempt in range(3):
try:
return operation()
except TemporaryError:
if attempt == 2:
raise
sleep_fn(1)
delays = []
def fake_sleep(seconds):
delays.append(seconds)
retry_operation(operation, sleep_fn=fake_sleep)
assert delays == [1, 1]
Other options are mocking the sleep call, using synchronization primitives, and testing timeout logic with a controlled clock. Keep short real delays for integration tests only when they test actual timing behavior.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Common errors and edge cases
Missing or ambiguous imports
import time
time.sleep(1)
After only import time, calling sleep(1) raises NameError; use time.sleep(1) or import the function directly.
Best Value
- 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
- Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
- Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
- HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
- What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
Invalid values
time.sleep("1") # TypeError
time.sleep(None) # TypeError
time.sleep(-1) # ValueError
Validate application input explicitly:
def pause(seconds):
if seconds < 0:
raise ValueError("seconds must be non-negative")
time.sleep(seconds)
Convert user input only when that is intended, for example seconds = float(user_input). Do not assume the exact NaN behavior of synchronous time.sleep() across every implementation; Python 3.13 and later explicitly document a ValueError for a nan delay in asyncio.sleep().
sleep(0) is not a universal no-op
Use pass when the requirement is simply “do nothing.” Python documents platform-specific behavior for time.sleep(0); on Windows it can relinquish the remainder of a thread’s time slice to another ready thread, but it may return immediately if none is ready. Choose a real synchronization primitive for coordination. In async code, use await asyncio.sleep(0) when you intentionally want to give other tasks an opportunity to run.
Signals
If a signal handler raises an exception, that exception propagates from sleep(). If the handler returns normally, Python recomputes the remaining timeout and resumes sleeping; since Python 3.5, the normal non-exception case sleeps for at least the requested duration.
Quick Recap
When to replace time.sleep()
- Use
asyncio.sleep()in an asyncio event loop. - Use events, conditions, queues, joins, or futures when waiting for work or state.
- Use
threading.Timerto schedule a callable after a delay. - Use a timeout API to cap an operation; sleeping before it does not create a deadline.
- Use a production retry or rate-limit mechanism when limits, jitter, cancellation, and server responses matter.
- Use a GUI framework’s scheduler so the interface remains responsive.
- Use deadline calculations with
time.monotonic()when periodic starts must remain stable.
Quick troubleshooting
| Symptom | Likely cause | Better approach |
|---|---|---|
| Program appears frozen | The current thread is blocked | Move the wait to a worker or use async scheduling |
| Async application stops responding | time.sleep() blocked the event loop |
Replace it with await asyncio.sleep() |
| Periodic loop drifts | Work time is added before each sleep | Schedule against time.monotonic() deadlines |
| Thread sometimes is not finished | An arbitrary delay guessed at completion | Use join(), an event, queue, condition, or future |
| Delay exceeds the request | OS scheduling or system load | Treat sleep as a minimum delay |
| Tests take too long | Real sleeps are used in unit tests | Inject or mock the sleeper |
| Retries arrive in a burst | Workers share a fixed delay | Use bounded exponential backoff with jitter |
| CPU usage is high | Polling interval is too short or absent | Increase the interval or wait on I/O/events |
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.

