![]() |
VOOZH | about |
A time delay means pausing the program for a short period before continuing to the next step. This is useful when you want to slow down the execution, like waiting between messages or steps in a loop. In Python, you can add a delay using the sleep() function from the time module, where you specify how many seconds the program should wait.
Now let's look at different ways to pause/delay execution in Python.
The time.sleep() function pauses the program for a set number of seconds before continuing. It's the simplest way to add a delay in execution.
time.sleep(seconds)
seconds: The number of seconds to pause the program (can be an integer or float).
Output
Explanation: It prints numbers one by one from 0 to 4, pausing 2 seconds between each print.
Output
Explanation:
Output
Explanation:
Output
Explanation:
threading.Event().wait() function pauses a thread for a specified time without blocking other threads. It's similar to time.sleep() but works well in multithreading scenarios.
threading.Event().wait(timeout)
timeout: Number of seconds to wait. If not given, it waits indefinitely until the event is set.
Output
Geeks
for
Geeks
Explanation: It creates a typing effect with pauses, using threading.Event().wait() as an alternative to time.sleep() for delaying execution without blocking other threads (if used in multithreaded programs).
threading.Timer class runs a function after a specified delay in a separate thread. It's useful for scheduling tasks without blocking the main program.
threading.Timer(interval, function, args=None, kwargs=None)
Output
Timer
Computer Science: GeeksforGeeks
Explanation:
time.monotonic() and time.monotonic_ns() return a clock value that always moves forward, making them useful for measuring time gaps. They arenβt affected by system clock changes. monotonic_ns() gives the time in nanoseconds for higher precision.
Time delay of 5 seconds is over!
Explanation: Measures a 5-second delay using time.monotonic() by checking the time difference in a loop, then prints a message when the delay is over.
Output
Time delay of 5 seconds is over!
Explanation: It waits for 5 seconds using high-precision time.monotonic_ns(). After the delay, it prints a message saying the time is over.
Related Articles: