How to Create a Time Delay in Python



Python


In this article, we show how to create a time delay in Python.

With a time delay, we can create a time delay in a script that creates a pause in the script.

To do this, we use the time module.

You do not have to install this module. It already exists in the Python package that you downloaded. However, you do have to import the time module.

Once the time module is imported, you can use the time.sleep() function to create a time delay, which simulates a pause.

The value you specify in the time.sleep() function is in seconds.

So, if you use the statement, time.sleep(1), this creates a time delay of 1 second.

The statement, time.sleep(5), creates a time delay of 5 seconds.

In the script below, we show the time.sleep() function creating a delay.



So, first, we import the time module.

We then create a for loop that loops through 5 times.

We print the statement, "Hi", which is followed by a delay of 1 second.

We then print the statement, "How are you?", which is followed by a delay of 3 seconds.

The "Hi" statement then prints again and this continues till "Hi", "How are you?" appears 5 times.

Thus, you can see how the time.sleep() function can create time delays in scripts.

The time.sleep() function can also accept decimals as its parameter. So if you need a delay of 2.1 seconds, the statement would be, time.sleep(2.1).

If you need a delay of less than 1 second, this can be done.

The statement, time.sleep(0.5), creates a time delay of a half a second, or 500 milliseconds.

The statement, time.sleep(0.1), creates a time delay of 1/10 of a second, or 100 milliseconds.

The statement, time.sleep(0.01), creates a time delay of 1/100 of a second, or 10 milliseconds.

The statement, time.sleep(0.001), creates a time delay of 1/1000 of a second, or 1 millisecond.

Thus, time.sleep() is a very versatile function to create time delays.


Related Resources



HTML Comment Box is loading comments...