How do I make a time delay?
Pause your Python script with the time.sleep()
command specifying the seconds of delay as shown below:
Substitute 5
with any float or integer to set the duration of the pause.
Pimp My Code: Customize your delay
Call directly
No need for time.sleep()
, call sleep()
directly and save typing:
Loop the loop
Squeeze sleep()
into your loops for timely pauses:
Finer than fine
Sub-second delays? We've got you covered:
Just-In-Time Pausing
Introduce rest stoppages at strategic junctures like after network requests or during busy loops.
Advanced convenience
Threads, pools and executors
You can line up concurrent tasks using ThreadPoolExecutor
and ProcessPoolExecutor
to execute tasks in the background:
Asynchronous dot-sleep
When napping in an async-function, replace time.sleep()
with asyncio.sleep()
:
Selenium’s patience virtues
Instead of generic waits, use targeted waiting with Selenium:
Tkinter’s time-out trick
In Tkinter, use the .after
command to keep the UI responsive while pausing:
When to avoid time.sleep()
While time.sleep()
is pretty cool, here’s when you might not want to use it:
- Pause-approach inasks – For Tkinter, use
root.after()
astime.sleep()
takes the whole event loop with it. - Web Automations – Selenium’s
wait.until()
provides smarter waits. - Async-code –
asyncio.sleep()
is the way to go. - Non-blocking delays –
threading.Timer
orsched
module can be effective.
Was this article helpful?