Question

How to Create a Time Delay in Python

pythondelaysleeptimedelay

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.

Take Quiz

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 time gives access to the time module.
  • 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 range(3):
    print("Working...", i)
    time.sleep(1)

This prints a message, waits 1 second, then repeats.

Step by Step Execution

Consider this code:

import time

print("A")
time.sleep(1)
print("B")

Step by step:

  1. Python imports the time module.
  2. print("A") runs, so A appears on the screen.
  3. time.sleep(1) runs.
  4. The program pauses for 1 second.
  5. After 1 second, execution continues.
  6. print("B") runs, so B appears.

Trace

StepCodeResult
1import timeModule becomes available
2print("A")Displays A
3time.sleep(1)Waits 1 second
4print("B")Displays B

Output:

A
B

The important detail is that there is a 1-second pause between the two lines of output.

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

A script that checks a folder, database, or service every few seconds may sleep between checks.

Take Quiz

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)

Validation and error handling context

A delay is often combined with:

  • checking whether data is ready
  • retrying after exceptions
  • stopping after a maximum number of attempts

Developers usually avoid unnecessary sleeping because it makes programs slower and can block useful work.

Common Mistakes

1. Forgetting to import time

Broken code:

sleep(2)

Problem:

  • Python does not know what sleep is.

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.

4. Sleeping too often in loops

Broken idea:

import time

for i in range(1000):
    time.sleep(1)

Problem:

  • This makes the script extremely slow.

Avoid it by asking whether each delay is actually needed.

5. Using negative values

import time
time.sleep(-1)

Problem:

  • This raises an error.

Use 0 or a positive number.

Comparisons

ConceptWhat it doesBest use
time.sleep()Pauses execution for a number of secondsSimple delays in regular Python scripts
Busy waitingRepeatedly checks something without really pausingUsually inefficient and should be avoided
asyncio.sleep()Pauses in asynchronous code without blocking the whole event loopAsync programs using async and await
threading.TimerSchedules a function to run laterDelayed actions without manually writing the wait logic

time.sleep() vs asyncio.sleep()

# Regular blocking sleep
import time
time.sleep(1)
# Async sleep
import asyncio

async def main():
    await asyncio.sleep(1)

Use time.sleep() in normal scripts. Use asyncio.sleep() in asynchronous Python programs.

Take Quiz

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 the time module.
  • The argument is in seconds.
  • Fractions are allowed.
  • time.sleep() blocks the current thread.
  • Use positive numbers or 0.

Common conversions

  • 1 second → 1
  • 500 milliseconds → 0.5
  • 100 milliseconds → 0.1
  • 50 milliseconds → 0.05

Quick pattern

import time

print("Before delay")
time.sleep(1)
print("After delay")

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 second
  • sleep(0.1) waits 0.1 seconds, which is 100 milliseconds
Take Quiz

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

  1. Import the time module.
  2. Print a countdown from 3 to 1.
  3. Wait 1 second between each number.
  4. Print Go! at the end.
Take Quiz

Keep learning

Related questions

View more