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.
Following is the syntax of the function,
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())
The code begins execution at: Tue Dec 31 11:32:58 2019 The code execution ends at: Tue Dec 31 11:33:10 2019
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)
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.
SHARE YOUR THOUGHTS WITH US!