Python - Sleep, pause or wait in your code

By xngo on June 18, 2019

In Python, you can pause the execution of your code by using time.sleep() from the time module. Be able to delay the flow of code is handy in certain situations such as when you are debugging, working with threads or animations. Please be aware that the accuracy of this function depends on the underlying operating system's sleep() function. The smallest interval you can sleep differs from MS Windows and Linux. As a rule of thumb, if you tolerate error up 10 milliseconds, then use time.sleep().

Here are some examples using time.sleep().

import time 
 
# Printing the start time  
print("Start time: ", end ="") 
print(time.ctime()) 
 
# Pause for 2 seconds.
time.sleep(2)
 
# Pause for 500 milliseconds.
time.sleep(0.5)
 
# printing the end time  
print("End time  : ", end ="") 
print(time.ctime())

Output

Start time: Tue Jun 18 19:02:16 2019
End time  : Tue Jun 18 19:02:18 2019

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.