This tutorial will teach you how to use the sleep() function from Python’s built-in time module to add time delays to code.

When you run a simple Python program, the code execution happens sequentially—one statement after the other—without any time delay. However, you may need to delay the execution of code in some cases. The sleep() function from Python built-in time module helps you do this.

In this tutorial, you’ll learn the syntax of using the sleep() function in Python and several examples to understand how it works. Let’s get started!

Syntax of Python time.sleep()

The time module, built into the Python standard library, provides several useful time-related functions. As a first step, import the time module into your working environment:

import time

As the sleep() function is part of the time module, you can now access and use it with the following general syntax:

time.sleep(n) 

Here, n is the number of seconds to sleep. It can be an integer or a floating point number.

Sometimes the required delay may be a few milliseconds. In these cases, you can convert the duration in milliseconds to seconds and use it in the call to the sleep function. For example, if you want to introduce a delay of 100 milliseconds, you can specify it as 0.1 second: time.sleep(0.1).

▶ You can also import only the sleep function from the time module:

from time import sleep

If you use the above method for importing, you can then call the sleep() function directly—without using time.sleep().

Now that you’ve learned the syntax of the Python sleep() function, let’s code examples to see the function in action. You can download the Python scripts used in this tutorial from the python-sleep folder in this GitHub repo. 👩🏽‍💻

Delay Code Execution with sleep() 

As a first example, let’s use the sleep function to delay the execution of a simple Python program.

<img alt="Delaying-Code-Execution" data- data-src="https://kirelos.com/wp-content/uploads/2022/12/echo/Delaying-Code-Execution.png" data- decoding="async" height="717" src="data:image/svg xml,” width=”1489″>

In the following code snippet:

  • The first print() statement is executed without any delay.
  • We then introduce a delay of 5 seconds using the sleep() function. 
  • The second print() statement will be executed only after the sleep operation finishes.
# /python-sleep/simple_example.py
import time

print("Print now")
time.sleep(5)
print("Print after sleeping for 5 seconds")

Now run the simple_example.py file and observe the output:

$ python3 simple_example.py

<img alt="YouTube video" data-pin-nopin="true" data-src="https://kirelos.com/wp-content/uploads/2022/12/echo/hqdefault.jpg63885cfea40eb.jpg" height="360" loading="lazy" src="data:image/svg xml,” width=”480″>

Add Different Delays to a Code Block

In the previous example, we introduced a fixed delay of 5 seconds between the execution of two print() statements. Next, let’s code another example to introduce different delay times when looping through an iterable.

In this example, we would like to do the following:

  • Loop through a sentence, access each word, and print it out. 
  • After printing out each word, we’d like to wait for a specific duration of time—before printing out the next word in the sentence.

Looping Through a String of Strings

Consider the string, sentence. It is a string where each word is a string in itself.

If we loop through the string, we will get each character, as shown:

>>> sentence = "How long will this take?"
>>> for char in sentence:
...     print(char)

# Output (truncated for readability)
H
o
w
.
.
.
t
a
k
e
?

But this is not what we want. We would like to loop through the sentence and access each word. To do this, we can call the split() method on the sentence string. This will return a list of strings—obtained by splitting the sentence string—on all occurrences of whitespace.

>>> sentence.split()
['How', 'long', 'will', 'this', 'take?']
>>> for word in sentence.split():
...     print(word)

# Output
How
long
will
this
take?

Looping Through Iterables with Different Delays

Let’s revisit the example:

  • sentence is the string we’d like to loop through to access each word.
  • delay_times is the list of delay times we’ll use as argument to the sleep() function during each pass through the loop.

Here we would like to simultaneously loop through two lists: the delay_times list and the list of strings obtained by splitting the sentence string. You can use the zip() function to perform this parallel iteration.

The Python zip() Function: zip(list1, list2) returns an iterator of tuples, where each tuple contains the item at index i in list1 and list2.

# /python-sleep/delay_times.py
import time

sleep_times = [3,4,1.5,2,0.75]
sentence = "How long will this take?"
for sleep_time,word in zip(sleep_times,sentence.split()):
    print(word)
    time.sleep(sleep_time)

Without the sleep function, the control would immediately proceed to the next iteration. Because we have introduced a delay, the next pass through the loop occurs only after the sleep operation is complete.

Now run delay_times.py and observe the output:

$ python3 delay_times.py

The subsequent words in the string will be printed out after a delay. The delay after printing out the word at index i in the string is the number at index i in the delay_times list.

<img alt="YouTube video" data-pin-nopin="true" data-src="https://kirelos.com/wp-content/uploads/2022/12/echo/hqdefault.jpg63885cfeaa4cd.jpg" height="360" loading="lazy" src="data:image/svg xml,” width=”480″>

Countdown Timer in Python

As a next example, let us code a simple countdown timer in Python.

<img alt="Countdown-Timer-in-Python" data- data-src="https://kirelos.com/wp-content/uploads/2022/12/echo/Countdown-Timer-in-Python.png" data- decoding="async" height="576" src="data:image/svg xml,” width=”1230″>

Let’s define a function countDown():

# /python-sleep/countdown.py
import time

def countDown(n):
    for i in range(n,-1,-1):
        if i==0:
            print("Ready to go!")
        else:
             print(i)
             time.sleep(1)

Next, let’s parse the definition of the countDown() function:

  • The function takes in a number n as the argument and counts down to zero starting from that number n.
  • We use time.sleep(1) to achieve a delay of one second between the counts.
  • When the count reaches 0, the function prints out “Ready to go!”.

🎯 To achieve the countdown operation, we’ve used the range() function with a negative step value of -1. range(n, -1, -1) will help us loop through the range of numbers in n, n – 1, n – 2, and so on up to zero. Recall that the end point is excluded by default when using the range() function.

Next let’s add a call to the countDown() function with 5 as the argument.

countDown(5)

Now run the script countdown.py and see the countDown function in action!

$ python3 countdown.py

<img alt="YouTube video" data-pin-nopin="true" data-src="https://kirelos.com/wp-content/uploads/2022/12/echo/hqdefault.jpg63885cff842cf.jpg" height="360" loading="lazy" src="data:image/svg xml,” width=”480″>

Sleep Function in Multithreading

Python threading module offers out-of-the-box multithreading capabilities. In Python, the Global Interpreter Lock or GIL ensures that there is only one active thread running at any point in time.

<img alt="python-sleep-3" data- data-src="https://kirelos.com/wp-content/uploads/2022/12/echo/3-3-1500×844.png" data- decoding="async" height="422" src="data:image/svg xml,” width=”750″>

However, during I/O operations and wait operations such as sleep, the processor can suspend the execution of the current thread and switch to another thread that is waiting.

To understand how this works, let’s take an example.

Creating and Running Threads in Python

Consider the following functions, func1(), func2(), and func3(). They loop through a range of numbers and print them out. This is followed by a sleep operation—for a specific number of seconds—during every pass through the loop. We’ve used different delay times for each of the functions to better understand how the execution switches between threads concurrently.

import time

def func1():
    for i in range(5):
        print(f"Running t1, print {i}.")
        time.sleep(2)

def func2():
    for i  in range(5):
         print(f"Running t2, print {i}.")
         time.sleep(1)


def func3():
    for i in range(4):
         print(f"Running t3, print {i}.")
         time.sleep(0.5)

In Python, you can use the Thread() constructor to instantiate a thread object. Using the syntax threading.Thread(target = …, args = …) creates a thread that runs the target function with the argument specified in the args tuple.

In this example the functions, func1, func2, and func3, do not take in any arguments. So it suffices to specify only the name of the function as the target. We then define thread objects, t1, t2, and t3 with func1, func2, and func3 as the targets, respectively.

t1 = threading.Thread(target=func1)
t2 = threading.Thread(target=func2)
t3 = threading.Thread(target=func3)

t1.start()
t2.start()
t3.start()

Here’s the complete code for the threading example:

# /python-sleep/threads.py
import time
import threading

def func1():
    for i in range(5):
        print(f"Running t1, print {i}.")
        time.sleep(2)

def func2():
    for i  in range(5):
         print(f"Running t2, print {i}.")
         time.sleep(1)

def func3():
    for i in range(4):
         print(f"Running t3, print {i}.")
         time.sleep(0.5)

t1 = threading.Thread(target=func1)
t2 = threading.Thread(target=func2)
t3 = threading.Thread(target=func3)

t1.start()
t2.start()
t3.start()

Observe the output. The execution alters between the three threads. The thread t3 has the lowest waiting time, so it is suspended for the least amount of time. Thread t1 has the longest sleep duration of two seconds, so it’s the last thread to finish execution.

<img alt="YouTube video" data-pin-nopin="true" data-src="https://kirelos.com/wp-content/uploads/2022/12/echo/hqdefault.jpg63885d0053b98.jpg" height="360" loading="lazy" src="data:image/svg xml,” width=”480″>

To learn more, read the tutorial on the basics of multithreading in Python.

Conclusion

In this tutorial, you have learned how to use Python’s sleep() function to add time delays to code.

You can access the sleep() function from the built-in time module, time.sleep(). To delay execution by n seconds, use time.sleep(n). Also, you’ve seen examples of delaying subsequent iterations in a loop by different values, countdown, and multithreading.

You may now explore more advanced capabilities of the time module. Want to work with dates and times in Python? In addition to the time module, you can leverage the functionality of the datetime and calendar modules.

Next, learn to calculate time difference in Python.⏰