Search code snippets, questions, articles...

Add delay in code execution python

To add some delay in python code execution, you can use the sleep() function of the time module.
import time

print("Print without delay: ", end="")


print("Print after 4 seconds: ", end="")

To use the sleep() method, we need to import the time python module. We can use time.sleep() after that. As a parameter, it takes the time delay in seconds. In the above code, we are passing 4 seconds as a delay in further program execution.

Use case of adding delay in program execution

There are a lot of python applications that requires some delays in program execution. For example, if you want to run a thread continuously with some delay between each thread execution. Then you can use the sleep() function. Or if you have some heavy tasks performed by the system and you want to delay the next process then you can also use it.

Search Index Data (The code snippet can also be found with below search text)

execute code after some time
import time

student = {
  'name': 'Harold',
  'branch': 'IT',
  'code': 'p2001'

print('Student name is : ', end='')

print('Student branch is : ', end='')

print('Student code is : ', end='')
Here, We are printing dictionary(student) items with some delay in each of the item prints.
import time


my_list = [10, 20, 30, 40, 50]
We are adding a delay of 5 seconds before executing the program that prints a python list.
import time

# A list contains multiple names
names = ['John', 'Rick', 'Sara', 'Aarya']

for name in names:
  # Add 2 seconds delay

  # Print a name every two seconds
Here, we have defined a list(names) that contains multiple names. We applying For Loop on it to access its items. Each iteration of for loop will print a name with 2 seconds delay.
Was this helpful?
Programming Feeds
Learn something new everyday on Devsheet