How To Use Python sleep() Function? – POFTUT

How To Use Python sleep() Function?

While developing applications we may need some rest for the execution. Python provides sleep() function for different use cases in order to delay program execution. In this tutorial, we will examine Python sleep() function for different conditions.

Sleep Time Precision

Before starting a tutorial we should know that Python is an interpreted language and is not real-time. So while using python there will be some inconsistencies. While using sleep function Linux can use 1-millisecond precision but Windows has 13 milliseconds precision. Keep in mind that if you will develop time precision applications.

Import time Module

As a beginner, we know that Python provides modules for different functionalities. time module provides the sleep() function. In order to use sleep() function we should import the time library like below.

import time

sleep() Function

Now we can use sleep() function by providing the time we want to wait. In this example, we will wait for 1 second. As I can not take a screenshot of delay there will be no screenshot ;). sleep() function will suspend the current thread. So if there are other threads they will do not wait.


Sleep 10 Seconds

Sleep function will interpret the provided value as second which must be a number. In this example, we will set 10 seconds wait.


Sleep For Milliseconds

What if we need to wait for given milliseconds. We can provide a floating number in order to express milliseconds. In this example, the delay will be 500 milliseconds which is expressed as 0.5


Or we can express 500 milliseconds like below.


Sleep For Specified Minutes

What if we do not want to calculate between minutes and seconds. We can use a simple calculation to simplify things. In this example we will wait for 4 minute which is expressed in seconds 4*60


LEARN MORE  Python Date Time Operations Tutorial with Examples

Leave a Comment