Thursday, December 26, 2024
Google search engine
HomeLanguagesHow to add time delay in Python?

How to add time delay in Python?

In this article, we are going to discuss how to add delay in Python

How to add Time Delay?

  • In order to add time delay in our program code, we use the sleep() function from the time module. This is the in-built module in Python we don’t need to install externally.
  • Time delay means we are adding delay during the execution time in our program code. It should be between two statements or between any part of the program code according to you.

Method 1: Using time.sleep() function

Approach:

  • Import the time module
  • For adding time delay during execution we use the sleep() function between the two statements between which we want the delay. In the sleep() function passing the parameter as an integer or float value.
  • Run the program.
  • Notice the delay in the execution time.

What is the Syntax of time.sleep

time.sleep(value)

To understand the topic perfectly. Let’s see the implementation by taking some examples.

Note: As an output, I have shown the GIF, so that you can notice the time delay in the program code during the execution time.

Example 1: Printing the numbers by adding a time delay.

Python3




# importing module
import time
 
 
# running loop from 0 to 4
for i in range(0,5):
   
  # printing numbers
  print(i)
   
  # adding 2 seconds time delay
  time.sleep(2)


Output:

Example 2: Dramatic printing using sleep() for every character.

Python3




# importing time module
import time
 
 
def message(string):
   
    for i in string:
       
        # printing each character of the message
        print(i, end="")
         
        # adding time delay of half second
        time.sleep(0.5)
 
 
# main function
if __name__ == '__main__':
    msg = "Its looks like auto typing"
     
    # calling the function for printing the
    # characters with delay
    message(msg)


Output:

Example 3: Printing the pattern by taking range from the user and adding time delay.

Python3




# importing module
import time
 
 
# function to print the pattern
def pattern(n):
   
    for i in range(0, n):
        for j in range(0, i+1):
           
            print('*', end=' ')
             
            # adding two second of time delay
            time.sleep(0.5)
        print(' ')
 
 
# main function
if __name__ == '__main__':
   
    # taking range from the user
    num = 4
    print("Printing the pattern")
     
    # calling function to print the pattern
    pattern(num)


Output:

Example 4: Multithreading using sleep()

Python3




# importing
import time
from threading import Thread
 
 
# making first thread of Geeks
class Geeks(Thread):
   
    def run(self):
        for x in range(4):
            print("Geeks")
             
            # adding delay of 2.2 seconds
            time.sleep(2.2)
 
# making second thread of For
class For(Thread):
   
    def run(self):
        for x in range(3):
            print('For')
             
            # adding delay of 2.3 seconds
            time.sleep(2.3)
 
 
print("Hello")
 
# making the object for both the
# threads separately
g1 = Geeks()
f1 = For()
 
# starting the first thread
g1.start()
 
# starting the second thread
f1.start()
 
# waiting for the both thread to join
# after completing their job
g1.join()
f1.join()
 
# when threads complete their jobs
# message will be printed
print("All Done!!")


Output:

Method 2: Using threading.Event.wait function

The threading.Event.wait procedure, the thread waits until the set() method execution is not complete. Time can be used in it; if a specific time is set, execution will halt until that time has passed; after that, it will resume while the set() of an event is still active.

What is the Syntax of threading.Event.wait function

threading.Event.wait()

Example:

Python3




from time import sleep
 
if __name__ == '__main__':
    # delay in seconds
    delay = 2
 
    print('Geeks')
    sleep(delay)
    print('for')
    sleep(delay)
    print('Geeks')


Output:

Geeks
for
Geeks

Method 2: Using threading.Timer class

Actions that need to be scheduled to begin at a specific time are represented by timer objects. These items are scheduled to execute on a different thread that performs the action.

What is the Syntax of threading.Timer function

threading.Timer(interval, function)

Example:

Python3




# Program to demonstrate
# timer objects in python
 
import threading
 
def gfg():
    print("Computer Science: Lazyroar\n")
 
 
timer = threading.Timer(1.0, gfg)
timer.start()
print("Timer")


Output:

Timer
Computer Science: Lazyroar

METHOD 4:Using time.monotonic() and time.monotonic_ns() functions:

APPROACH:

The time.monotonic() function returns the value of a monotonic clock, which is not subject to system clock changes. The time.monotonic_ns() function returns the value of the monotonic clock in nanoseconds. 

ALGORITHM:

1.Set the value of delay in seconds.
2.Get the current time using time.monotonic() and assign it to start_time.
3.Enter a loop that runs indefinitely.
4.Get the current time again and calculate the elapsed time by subtracting start_time from it.
5.If the elapsed time is greater than or equal to the desired delay, break out of the loop.
6.Print a message indicating that the delay is over.

Python3




import time
 
start_time = time.monotonic()
delay = 5  # delay in seconds
 
while True:
    current_time = time.monotonic()
    elapsed_time = current_time - start_time
    if elapsed_time >= delay:
        break
 
print("Time delay of 5 seconds is over!")


Output

Time delay of 5 seconds is over!

The time complexity of this code is O(n) where n is the number of times the loop runs, which depends on the duration of the delay. The auxiliary space is O(1) as it does not require any additional memory.

RELATED ARTICLES

Most Popular

Recent Comments