Sometimes, it may be required to give a timeout or stop the processing for a certain amount of time. This is when the sleep functionality comes into play. The sleep
function is present in the time module in Python. It is an accurate method to halt the flow of control in python code.
Syntax of the sleep
function
Following is the syntax of the function,
time.sleep(second)
The second parameter tells the amount of time for which the code has to halt the execution. It doesn't return anything.
Let's take a code example,
import time
print("The code begins execution at: ", end ="")
print(time.ctime())
time.sleep(12)
print("The code execution ends at: ", end ="")
print(time.ctime())
Output:
The code begins execution at: Tue Dec 31 11:32:58 2019
The code execution ends at: Tue Dec 31 11:33:10 2019
Applications of the sleep
function
Following are some of the applications of the following function:
-
Running background processes at specific intervals of time.
-
Providing a better user interface by giving some time gap between typing letters.
The above application can be seen in action with the below code example:
Note: Make sure to run it on your IDE to see how it works.
import time
my_str = "Studytonight"
for i in range(0, len(my_str)):
print(my_str[i], end ="")
time.sleep(1)
Output:
Studytonight
Conclusion:
In this post, we understood how the sleep
function of the time module in python works. Let us know your thoughts on this function's usage in the comment section below.