Question
How can I add a time delay in a Python script?
For example, I want the program to pause for a short amount of time before continuing to the next line of code.
Short Answer
By the end of this page, you will understand how to pause execution in Python, usually with time.sleep(). You will learn the basic syntax, how delays work step by step, where they are useful in real programs, and what common mistakes to avoid.
Concept
In Python, a time delay means temporarily pausing the program before it continues running.
The most common way to do this is with the sleep() function from Python's built-in time module:
import time
time.sleep(2)
This tells Python to wait for 2 seconds before moving to the next line.
Why this matters:
- You may want to slow down output so users can read messages.
- You may need to wait between API requests.
- You may want to retry an operation after a short pause.
- You may be building scripts, automation tools, or simple games.
A delay is useful when your program should pause intentionally. It is different from a program being slow by accident. Here, the pause is something you choose.
In normal Python scripts, time.sleep() blocks execution. That means the program does nothing else during the delay unless you are using a different async approach.
Mental Model
Think of time.sleep() like a kitchen timer.
- Your program is following a recipe.
- When it reaches
sleep(3), it sets a timer for 3 seconds. - During those 3 seconds, it waits.
- When the timer finishes, the program continues with the next step.
So sleep() is not doing work in the background for your script. It is a deliberate pause before continuing.
Syntax and Examples
The basic syntax is:
import time
time.sleep(seconds)
Example: Pause for 2 seconds
import time
print("Start")
time.sleep(2)
print("2 seconds later")
How it works
import timegives access to thetimemodule.time.sleep(2)pauses the program for 2 seconds.- After the pause, the next
print()runs.
Example: Fractional seconds
You can also sleep for part of a second:
import time
print("Wait for half a second...")
time.sleep(0.5)
print("Done")
Example: Repeating with a delay
import time
for i in ():
(, i)
time.sleep()
Step by Step Execution
Consider this code:
import time
print("A")
time.sleep(1)
print("B")
Step by step:
- Python imports the
timemodule. print("A")runs, soAappears on the screen.time.sleep(1)runs.- The program pauses for 1 second.
- After 1 second, execution continues.
print("B")runs, soBappears.
Trace
| Step | Code | Result |
|---|---|---|
| 1 | import time | Module becomes available |
| 2 | print("A") |
Real World Use Cases
Here are some practical uses for time delays in Python:
Rate limiting API requests
If an API allows only a certain number of requests per second, you can pause between requests.
import time
for user_id in [1, 2, 3]:
print(f"Fetching user {user_id}")
time.sleep(1)
Retry after failure
If something temporary fails, wait before trying again.
import time
for attempt in range(3):
print("Trying...")
time.sleep(2)
User-facing scripts
You may want to show messages gradually.
import time
print("Loading...")
time.sleep(1)
print("Almost done...")
time.sleep(1)
print("Ready")
Polling for changes
Real Codebase Usage
In real projects, developers use delays carefully rather than placing them everywhere.
Common patterns include:
Simple retry logic
import time
for attempt in range(3):
success = False # pretend result
if success:
break
time.sleep(1)
Guarding external services
When calling APIs or scraping websites, a short delay can prevent hitting limits too quickly.
Polling loops
import time
while True:
print("Checking for updates...")
time.sleep(5)
Backoff-style waiting
Programs sometimes increase the delay after repeated failures.
import time
for attempt in range(3):
delay = attempt + 1
print(f"Waiting {delay} seconds before retry")
time.sleep(delay)
Common Mistakes
1. Forgetting to import time
Broken code:
sleep(2)
Problem:
- Python does not know what
sleepis.
Fix:
import time
time.sleep(2)
2. Using milliseconds instead of seconds
Broken expectation:
import time
time.sleep(50)
Problem:
sleep(50)waits 50 seconds, not 50 milliseconds.
Fix:
import time
time.sleep(0.05)
3. Thinking sleep() runs other code during the pause
Problem:
- In a normal script,
time.sleep()blocks the current thread. - Your code does not continue until the delay is over.
Comparisons
| Concept | What it does | Best use |
|---|---|---|
time.sleep() | Pauses execution for a number of seconds | Simple delays in regular Python scripts |
| Busy waiting | Repeatedly checks something without really pausing | Usually inefficient and should be avoided |
asyncio.sleep() | Pauses in asynchronous code without blocking the whole event loop | Async programs using async and await |
threading.Timer | Schedules a function to run later | Delayed actions without manually writing the wait logic |
time.sleep() vs asyncio.sleep()
time
time.sleep()
Cheat Sheet
import time
time.sleep(2) # wait 2 seconds
time.sleep(0.5) # wait half a second
time.sleep(0.05) # wait 50 milliseconds
Rules
sleep()is in thetimemodule.- The argument is in seconds.
- Fractions are allowed.
time.sleep()blocks the current thread.- Use positive numbers or
0.
Common conversions
1 second→1500 milliseconds→0.5100 milliseconds→0.150 milliseconds→0.05
Quick pattern
import time
()
time.sleep()
()
FAQ
How do I delay a Python script for 1 second?
Use:
import time
time.sleep(1)
How do I sleep for milliseconds in Python?
Pass a fractional number of seconds. For example, 50 milliseconds is 0.05.
import time
time.sleep(0.05)
Does time.sleep() stop the whole program?
In a normal single-threaded script, it pauses execution of that thread until the delay ends.
Why is my delay not working?
Common reasons:
- you forgot
import time - you used milliseconds as if they were seconds
- you expected other code to run during the sleep
Can I use sleep() inside a loop?
Yes, but be careful. It can slow the program a lot if used too often.
What is the difference between sleep(1) and sleep(0.1)?
sleep(1)waits 1 secondsleep(0.1)waits 0.1 seconds, which is 100 milliseconds
Mini Project
Description
Build a small countdown script that pauses between numbers. This demonstrates how time.sleep() controls timing in a real Python program and shows how delays can make terminal output happen gradually instead of all at once.
Goal
Create a Python countdown that prints numbers one at a time with a 1-second delay, then prints a final message.
Requirements
- Import the
timemodule. - Print a countdown from 3 to 1.
- Wait 1 second between each number.
- Print
Go!at the end.
Keep learning
Related questions
@staticmethod vs @classmethod in Python Explained
Learn the difference between @staticmethod and @classmethod in Python with clear examples, use cases, mistakes, and a mini project.
Catch Multiple Exceptions in One except Block in Python
Learn how to catch multiple exceptions in one Python except block using tuples, with examples, mistakes, and real-world usage.
Convert Bytes to String in Python 3
Learn how to convert bytes to str in Python 3 using decode(), text mode, and proper encodings with practical examples.