---Advertisement---

Python time.sleep() Function: Adding Delay in Code with Best Examples 2025

By Bhavani

Updated On:

---Advertisement---
Python time.sleep() Function

Python time.sleep() Function: The Python time.sleep() function is a valuable tool that allows developers to pause code execution for a specified number of seconds. This function is part of the time module and is particularly useful when you need to wait for a process to complete, manage delays in code execution, or simulate waiting periods.


Python time.sleep() Function: The time.sleep() function delays the execution of the program by pausing it for the number of seconds specified. This method is essential in scenarios like file uploads, waiting for data to load, or introducing controlled delays in automation scripts.


import time

time.sleep(seconds)

  • seconds: The number of seconds to pause the code execution.
  • The function does not return any value but introduces a delay in the program flow.

import time

print(“Starting process…”)

time.sleep(5)

print(“This message appears after a 5-second delay.”)

Starting process…

(This appears after 5 seconds)

This message appears after a 5-second delay.


To delay the execution of a function, you can call time.sleep() before invoking the function.

import time

def display():

    print(“Hello from Python tutorials!”)

time.sleep(3)

display()

(This appears after 3 seconds)

Hello from Python tutorials!


To introduce a delay between loop iterations:

import time

message = “Python Code”

for char in message:

    print(char)

    time.sleep(1)

P

y

t

h

o

n

C

o

d

e


Besides time.sleep(), Python offers additional methods to introduce delays:

import asyncio

async def display():

    await asyncio.sleep(5)

    print(“Hello from Asyncio!”)

asyncio.run(display())

(This appears after 5 seconds)

Hello from Asyncio!


from threading import Event

def display():

    print(“Message after delay”)

Event().wait(4)  # Pause for 4 seconds

display()

(This appears after 4 seconds)

Message after delay


from threading import Timer

def display():

    print(“Timer executed this message!”)

t = Timer(5, display)  # Delay for 5 seconds

t.start()

(This appears after 5 seconds)

Timer executed this message!


The time.sleep() function is an effective way to introduce delays in Python code. Whether you are handling file uploads, waiting for external processes, or simply adding a pause between actions, time.sleep() is a versatile tool. For advanced delay management, consider using asyncio.sleep(), Event().wait(), or Timer() for optimal performance in your projects.

Python Enumerate() Function

Download Python

Leave a Comment

Index