Wait Function in Python: 6 Ways to Make Python Wait

If you need your script to pause for a few seconds or hold off until a file, thread or process is ready, there’s no single wait(). The usual wait function in Python is time.sleep(seconds), and the other waits are smarter versions of it.

The catch is that “wait” can mean a delay, a condition or a job finishing, and the wrong tool either freezes your program or wastes time.

In this tutorial, I’ll show you six ways to make Python wait. Every example ran on Python 3.12.5 on Windows 11, and the timings quoted come from those runs.

The sample script we’ll use: shipping three store orders

Every example works with the same three orders from a small online store: #1041, #1042 and #1043. The tricky cases: a label file that shows up late, one that never arrives, and a lookup that runs too long.

Timing uses the time module. For clock times in logs, see printing the current date and time in Python covers datetime.now().

Method 1: Pause for a fixed time with time.sleep() (Recommended)

Use time.sleep() when you just need a delay, like spacing out API calls. Here’s the code, using the same three orders with a 1.5-second pause after each:

import time

orders = ["#1041", "#1042", "#1043"]

start = time.perf_counter()
for order in orders:
    now = time.perf_counter() - start
    print(f"{now:4.1f}s  sending order {order}")
    time.sleep(1.5)                  # pause 1.5 seconds between calls

total = time.perf_counter() - start
print(f"Sent {len(orders)} orders in {total:.1f} seconds")

Output:

 0.0s  sending order #1041
 1.5s  sending order #1042
 3.0s  sending order #1043
Sent 3 orders in 4.5 seconds

The orders go out 1.5 seconds apart, and the whole loop takes 4.5 seconds because it also sleeps after the last order.

VS Code output of Python time.sleep pausing 1.5 seconds between three orders
Each order is sent about 1.5 seconds after the previous one, and the total comes to 4.5 seconds.

How does this code work?

time.perf_counter() is a high-resolution clock, so subtracting the start gives 0.0, 1.5 and 3.0. time.sleep(1.5) blocks the whole thread for that long.

For milliseconds, use a fraction: time.sleep(0.25) waits 250 ms.

Pro Tip: When many scripts call the same API, add a little randomness, like time.sleep(1 + random.uniform(0, 0.5)). My post on generating random numbers in Python explains random.uniform().

Method 2: Make Python wait until a condition is true

A fixed sleep guesses. When you know what you’re waiting for, check for it in a loop with a timeout. Same orders again: a background timer saves label_1041.txt after 1.8 seconds, while label_1042.txt never arrives:

import threading, time
from pathlib import Path

def wait_until(check, timeout, interval=0.5):
    deadline = time.monotonic() + timeout
    while time.monotonic() < deadline:
        if check():
            return True
        time.sleep(interval)
    return False

label = Path("label_1041.txt")
label.unlink(missing_ok=True)
# pretend the label printer saves the file after 1.8 seconds
threading.Timer(1.8, label.write_text, args=["UPS 1Z999"]).start()

for name in ["label_1041.txt", "label_1042.txt"]:
    start = time.monotonic()
    ok = wait_until(Path(name).exists, timeout=3)
    took = time.monotonic() - start
    print(f"{name}: {ok} after {took:.1f} s")

Output:

label_1041.txt: True after 2.0 s
label_1042.txt: False after 3.0 s
VS Code output of a Python wait_until helper finding one label file and timing out on the other
One label file arrives and returns True after about 2 seconds; the other returns False when the timeout runs out.

How does this code work?

wait_until() is a while loop with a condition that runs until a deadline. time.monotonic() never jumps when the system clock changes.

Each pass calls check(), here Path.exists, then sleeps half a second. That’s why the first file shows up at the 2.0-second check, not exactly at 1.8. More ways to test for files are in checking if a file exists in Python.

Important: Pass the function itself (Path(name).exists), not its result, or you check only once.

Method 3: Wait for a function to finish with Thread.join() and Event.wait()

thread.join() waits until a thread ends, and threading.Event().wait(timeout) waits for a signal but lets you give up early. Here, the same three orders are printed by a worker thread at half a second each:

import threading, time

def print_labels(orders, done):
    for order in orders:
        time.sleep(0.5)              # a slow label printer
    done.set()

done = threading.Event()
orders = ["#1041", "#1042", "#1043"]
worker = threading.Thread(target=print_labels, args=(orders, done))

start = time.perf_counter()
worker.start()
print("Done within 1 second?", done.wait(timeout=1))
worker.join()                        # block until the thread ends
print("Done after join()?", done.is_set())
print(f"Waited {time.perf_counter() - start:.1f} seconds in total")

Output:

Done within 1 second? False
Done after join()? True
Waited 1.5 seconds in total
VS Code output of Python Event.wait returning False after a timeout, then Thread.join waiting for the worker
done.wait(timeout=1) returns False, and join() then waits until all three labels are printed.

How does this code work?

The worker calls done.set() when it finishes. done.wait(timeout=1) returns True if that happens in time and False otherwise; here it’s False, and the total wait is 1.5 seconds.

worker.join() has no timeout here, so it blocks until the thread ends. You can pass join(timeout=5) and then check worker.is_alive().

Method 4: Wait without blocking using asyncio.sleep() and wait_for()

In async code, time.sleep() freezes the event loop. Use await asyncio.sleep(), and asyncio.wait_for() for a time limit. Same store, now looking up sales tax rates for three states at once:

import asyncio, time

async def tax_rate(state, seconds):
    await asyncio.sleep(seconds)     # other tasks keep running
    return state

async def main():
    start = time.perf_counter()
    states = await asyncio.gather(
        tax_rate("TX", 1), tax_rate("CO", 1), tax_rate("FL", 1))
    took = time.perf_counter() - start
    print(states, f"in {took:.1f} seconds")

    try:
        await asyncio.wait_for(tax_rate("NY", 3), timeout=1)
    except TimeoutError:
        print("NY lookup gave up after 1 second")

asyncio.run(main())

Output:

['TX', 'CO', 'FL'] in 1.0 seconds
NY lookup gave up after 1 second

Three 1-second lookups finish in 1.0 seconds total because they wait at the same time, and the 3-second New York lookup is cancelled after 1 second.

VS Code output of Python asyncio.gather running three sleeps at once and wait_for timing out
Three one-second waits overlap and finish together; wait_for() cancels the slow lookup at the timeout.

How does this code work?

await asyncio.sleep(1) hands control back to the event loop, so asyncio.gather() runs all three side by side instead of taking 3 seconds.

asyncio.wait_for() cancels the task and raises TimeoutError when time runs out. Since Python 3.11 that’s the built-in TimeoutError, so one except clause works; see catching multiple exceptions in Python if you handle several errors.

Method 5: Wait for another program with subprocess wait()

subprocess.run() already waits for the child process. With Popen, call proc.wait(), optionally with a timeout. For our orders, the child is a 2-second export job:

import os, subprocess, sys, time

job = [sys.executable, "-c", "import time; time.sleep(2)"]
start = time.perf_counter()
proc = subprocess.Popen(job)

try:
    proc.wait(timeout=1)
except subprocess.TimeoutExpired:
    print("Export still running after 1 second")

code = proc.wait()                   # no timeout: wait until it exits
took = time.perf_counter() - start
print(f"Exit code {code} after about {took:.0f} seconds")
print("os.wait() available here?", hasattr(os, "wait"))

Output:

Export still running after 1 second
Exit code 0 after about 2 seconds
os.wait() available here? False

The timeout fires first, then wait() returns exit code 0 after about 2 seconds. os.wait doesn’t exist on Windows at all.

VS Code output of Python Popen.wait raising TimeoutExpired, then returning exit code 0
wait(timeout=1) times out, the second wait() returns exit code 0, and hasattr(os, "wait") prints False.

How does this code work?

Popen() returns right away. wait(timeout=1) raises TimeoutExpired, but the process keeps running, so the second wait() picks it up and returns its exit code.

An exit code of 0 means success; anything else is an error code the program chose, like the ones set with Python exit commands.

Method 6: Wait for the user to press Enter

Sometimes the right wait is a human one. input() blocks until the user presses Enter. Here’s the same order list with a manual checkpoint:

orders = ["#1041", "#1042", "#1043"]
print(f"{len(orders)} orders are ready to ship.")
input("Check the printer, then press Enter...")
for order in orders:
    print("Printing label for", order)

Output:

3 orders are ready to ship.
Check the printer, then press Enter...
Printing label for #1041
Printing label for #1042
Printing label for #1043

The script stops at the prompt, and the three labels print only after I press Enter.

How does this code work?

input() returns whatever was typed, and here the text is ignored. Python 2’s version was called raw_input(); raw_input() in Python covers the difference.

Which wait method should you use?

You want toUseBlocks the thread?
Pause for a fixed timetime.sleep(seconds)Yes
Wait until something is trueLoop with time.monotonic() deadlineYes, in short sleeps
Wait for a thread or signalThread.join(), Event.wait(timeout)Yes
Wait inside async codeawait asyncio.sleep(), asyncio.wait_for()No
Wait for another programPopen.wait(timeout), subprocess.run()Yes
Wait for a personinput()Yes

I’d start with time.sleep() and switch to a condition or timeout once you’re waiting on something real.

Things to Keep in Mind when making Python wait

  • Don’t sleep in a Tkinter GUI: the window freezes. Use root.after(ms, func), as in this Tkinter countdown timer.
  • Always give a wait loop a timeout, or one missing file hangs your script forever.
  • To wait until a clock time, compute the seconds left with datetime and sleep once; see scheduling tasks based on the current time.
  • In Selenium, use WebDriverWait instead of a fixed sleep.

Want more on loops, timers and delays? These fit well next:

Frequently asked questions

Does Python have a wait() function?

Not as a built-in. Use time.sleep() for a delay. os.wait() exists only on Unix and waits for a child process.

How do I make Python wait 5 seconds?

Add import time and call time.sleep(5). The current thread pauses for five seconds.

How do I make Python wait in milliseconds?

Pass a fraction of a second: time.sleep(0.25) waits 250 milliseconds.

How do I make Python wait until a condition is true?

Check the condition in a loop with a short sleep and a deadline, or use threading.Event().wait(timeout) when another thread can signal you.

How do I wait for a function to finish in Python?

Run it in a thread and call thread.join(), await it in async code, or call proc.wait() for a separate program.

Where is time.sleep() documented?

See time.sleep() in the Python docs.