Python time sleep() – How to Add Time Delay to Your Code

Python time sleep() – How to Add Time Delay to Your Code

The Python time.sleep() function is employed to introduce a pause in program execution. This function allows us to temporarily halt the program’s progress for a specified duration in seconds. It’s important to note that the Python time.sleep() function exclusively suspends the execution of the current thread rather than affecting the entire program.

Python time sleep() function syntax

Python’s sleep() function resides within the time module. To utilize this method, the initial step is to import the time module. Once imported, the sleep function can be invoked. The syntax for using the Python sleep() function is as follows:

import time
t=2 //2 second
time.sleep(t)

In this scenario, the argument t within the sleep() method signifies the time duration in seconds. Consequently, when the statement time.sleep(t) is executed, the subsequent line of code will be executed after a delay of t seconds. The following example provides a clearer understanding:

# importing time module
import time
print("Before the sleep statement")
time.sleep(5)
print("After the sleep statement")

Upon executing the provided code snippet, it becomes evident that the second print statement is performed after a 5-second delay. This demonstrates how you can introduce delays in your code as required. The argument within the sleep() function can also accept floating-point values, allowing for more precise time intervals. For instance, if you wish to implement a 100-millisecond delay (0.1 seconds), the following example illustrates the approach:

import time
time.sleep(0.100)

Check our developer-friendly Python Hosting!

Python sleep example

Let’s see the following example of Python’s time sleep function.

import time
startTime = time.time()
for i in range(0,5):
   print(i)
   # making delay for 1 second
   time.sleep(1)
endTime = time.time()
elapsedTime = endTime - startTime
print("Elapsed Time = %s" % elapsedTime)

This will output:

0
1
2
3
4
Elapsed Time = 5.059988975524902
The elapsed time surpasses 5 seconds because within each iteration of the for loop, the execution is suspended for 1 second using the sleep() function. However, the additional time is attributed to various factors, including the program’s execution time, thread scheduling by the operating system, and related considerations.

Save $100 in the next
5:00 minutes?

Register Here

The Different Delay Rimes of Python Sleep ()

Sometimes, you may need to delay for different seconds. You can do it as follows:

import time
for i in [ .5, .1, 1, 2]:
   print("Waiting for %s" % i , end='')
   print(" seconds")
   time.sleep(i)

This will output:

Waiting for 0.5 seconds
Waiting for 0.1 seconds
Waiting for 1 seconds
Waiting for 2 seconds

Dramatic Printing Using Sleep ()

You may need to print some messages dramatically; you can do it as follows:

# importing time module
import time
message = "Hi!!! I am trying to create suspense"
for i in message:
   # printing each character of the message
   print(i)
   time.sleep(0.3)

If you run the above code, you will see that printing every message character takes some time, which seems dramatic.

Python thread sleep()

The Python time.sleep() function holds significant importance in multithreading scenarios. Here’s a basic example that Demonstrates how the time.sleep() function suspends the execution of the current thread exclusively within a multithreaded programming context:

import time
from threading import Thread

class Worker(Thread):
    def run(self):
        for x in range(0, 11):
            print(x)
            time.sleep(1)
class Waiter(Thread):
    def run(self):
        for x in range(100, 103):
            print(x)
            time.sleep(5)
print("Staring Worker Thread")
Worker().start()
print("Starting Waiter Thread")
Waiter().start()
print("Done")

Sign up and avail $100 free credits now!!

The output produced by the above Python thread sleep example.

Staring Worker Thread
0
Starting Waiter Thread
100
Done
1
2
3
4
101
5
6
7
8
9
102
10

Register and get Auto Scalable instances with a Pay-As-You-Go Pricing Model!

The output demonstrates the Python time.sleep() function effectively halts the execution of threads while allowing the rest of the program to continue running. This highlights the functionality and purpose of the Python sleep function.

Thank you for learning with Accuweb.Cloud. We invite you to explore our compute, storage, applications, and database solutions.

Save $100 in the next
5:00 minutes?

Register Here