Kodeclik Logo

Our Programs

Courses

Learn More

Schedule

Kodeclik Blog

How to add Time Delays to your Python program

In some programming scenarios, it's essential to introduce delays or pauses in your code execution. For instance if you are doing some animation or graphics you might want to introduce delays to make sure characters are orchestrated in the order and sequence you desire. If you need to simulate real-time behavior or control timing for synchronization, you will need to add time delays to your program.

How to add delays to your Python program

In this blog post, we will explore different approaches to incorporate delays in Python.

Method 1: Use the time.sleep() function

The first approach uses the time module in Python, specifically the sleep() function, which allowing you to pause the execution for a specified number of seconds.

Here's a sample program using time.sleep():

import time

print("Starting")

time.sleep(3)

print("Ending")

If you run this program, you will see “Starting” printed first:

Starting

And then 3 seconds later the second line will be printed so the output looks like:

Starting
Ending

The time.sleep() function allows you to introduce precise delays and control the timing of your code. This approach essentially suspends execution for the specified number of seconds. The argument can also be a floating point number (i.e., it need not be an integer) to indicate a more precise sleep time.

Method 2: Run your own delay loop using the datetime module

Python's datetime module provides additional capabilities for introducing delays, especially when dealing with shorter durations.

Here's an example of how you can utilize it.

import datetime

delay = datetime.timedelta(seconds=3)
print("Starting")

# find the current time
current_time = datetime.datetime.now()
while datetime.datetime.now() - current_time < delay:
  pass

print("Ending")

In the above code we first create an interval (using the timedelta function) specifying an interval gap as 3 seconds. Then we print our “Starting” message and record the current time in the “current_time” variable. After this we get into a while loop where we keep re-finding the current time and comparing it to the stored current time (which was the start of the loop). If it is within the specified interval we continue the loop, else we exit the loop. The output is as before (after 3 seconds have passed):

Starting
Ending

The timedelta() function allows for very granular specification of time. In particular, it takes multiple arguments such as milliseconds, seconds, minutes, hours, days and even weeks! You can specify multiple such arguments to obtain a very granular specification of time. For instance consider the updated program:

import datetime

delay = datetime.timedelta(seconds=3, milliseconds=1000)

print("Starting")

# find the current time
current_time = datetime.datetime.now()
while datetime.datetime.now() - current_time < delay:
  pass

print("Ending")

This program essentially does a delay of 3 seconds plus 1000 milliseconds = 4 seconds (with the same outputs as before).

Method 3: Use the asyncio.sleep() function

If you are working with asynchronous programming in Python, the asyncio module provides powerful features for introducing delays. Here's an example:

import asyncio

async def sample_delay():
    print("Starting")
    await asyncio.sleep(3)  
    print("Ending")

# Run the example coroutine
asyncio.run(sample_delay())

In this snippet, we define an async function sample_delay() that uses the await asyncio.sleep() statement to pause the execution for 3 seconds. By leveraging asyncio, you can incorporate delays while maintaining the responsiveness of your program, especially when dealing with concurrent tasks and asynchronous operations.

The output is the same as before:

Starting
Ending

Adding delays in Python is a valuable technique for controlling timing, simulating real-time behavior, and synchronizing operations. In this blog post, we have presented three different methods for introducing delays in Python: using time.sleep() for general delays, utilizing datetime for more granular delays, and leveraging asyncio for asynchronous programming scenarios. Understanding these techniques allows you to incorporate delays effectively into your code, enhancing its efficiency and functionality. Which method is your favorite?

If you liked this blogpost, checkout our blogpost on how to end a Python program. Also learn how to add delays to your Javascript program.

Interested in more things Python? Checkout our post on Python queues. Also see our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!

Want to learn Python with us? Sign up for 1:1 or small group classes.

Kodeclik sidebar newsletter

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.

About

Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.

Copyright @ Kodeclik 2024. All rights reserved.