How do I make a time delay?
What methods are available to pause or delay the execution of code for a few seconds? Learn how Python’s built-in modules like time help in adding intentional delays between operations.
To make a time delay in Python, the most common and straightforward way is by using the built-in time module, specifically the sleep() function. This function pauses the program’s execution for a specified number of seconds. Time delays can be useful in scenarios like simulating loading, pacing output in loops, waiting for resources, or throttling requests in web scraping.
Here's how you can do it:
import time
print("Starting delay...")
time.sleep(3) # Delay for 3 seconds
print("3 seconds later...")
This script will print the first message, wait for 3 seconds, and then print the second message.
Other options and use cases:
Using asyncio.sleep(): For asynchronous programming, especially in async functions.
import asyncio
async def delayed():
print("Wait for it...")
await asyncio.sleep(2)
print("Done waiting!")
asyncio.run(delayed())
Using threading.Timer(): Useful if you want to schedule a function to run after a delay without pausing the main thread.
Key Points:
- time.sleep(seconds) is blocking, meaning it stops all code execution during the delay.
- Ideal for small pauses, like adding suspense or simulating load time.
- Use asyncio.sleep() if you're writing asynchronous code to avoid blocking.
- Adding delays is simple in Python, and choosing the right approach depends on whether your application is synchronous or asynchronous.