Hit enter after type your search item
Home / Python Tutorials / What is sleep method of time module in Python?

What is sleep method of time module in Python?

The sleep() is a method of time module that enables suspending the execution of the current thread for the given time. The time is provided in seconds.

Example1  Milliseconds Example2

How to use the time.sleep method?

After importing the time module in your program, you may use the sleep method as follows:

time.sleep( time_in_seconds )

Where time in seconds can be an int or float type. The float type enables you pausing the execution of thread more precisely. For example:

time.sleep( 2 ) #an Int value = 2 seconds

time.sleep( 3.55 ) #Time in floating point

For specifying the time in milliseconds (ms), for less than a second, you may also use this:

time.sleep( 0.7 )

That means 700 ms sleep or delay.

Note: The actual suspension time may be less or more than the requested time in the sleep method. The reason can be the operating system, scheduling of other activities in the system, or any caught signal that will terminate the sleep().

See the next section for different examples of using the sleep Python method.

A simple example of using the Python sleep method

In this example, I simply used the print function for displaying two sentences. The first print function executes normally. One second of delay is given for executing the second print function. See the demo and code below:

See online demo and code


The output:

Python sleep

As you execute this code, you will see the second line will display after the one-second wait.

A Demo of using float value for seconds parameter

For this demo of using the float value for the delay, I used 500 ms value in the sleep command parameter. A while loop is used that will run until the value of the variable x reaches 50.

In each loop, the current value of the variable x is displayed and the wait of 500 ms is given in the sleep method:

See online demo and code


The result of this code:

sleep while

As you run this code, you will see each line will display with the gap of 500 ms or half of a second.

Using the sleep method for iterating a list

For the final example, I used a list of five items and used the sleep method in a for loop. The value of one and half seconds (1.5) is given in the sleep method to delay the execution. Have a look:

See online demo and code


delay

As you run this code, the list items will display with the gap of 1.5 seconds starting from the second item. As such, I placed the sleep command after the print function.

This div height required for enabling the sticky sidebar