zaro

How do you add a delay in Python?

Published in Python Time Delay 2 mins read

You can add a delay in Python using the time.sleep() function. This function pauses the execution of your program for a specified number of seconds.

Using time.sleep()

The time.sleep() function is part of Python's built-in time module. It's a straightforward way to introduce pauses into your code.

How it Works

  • The time.sleep() function suspends the current thread's execution.
  • You provide the desired delay in seconds as an argument to the function.
  • Once the specified time has elapsed, the program resumes execution from the next line of code.

Example

import time

print("Start")
time.sleep(2)  # Pause for 2 seconds
print("End")

In the code above, you will see the following occur:

  1. "Start" is printed to the console.
  2. The program pauses for 2 seconds due to time.sleep(2).
  3. "End" is printed to the console after the pause.

Key Characteristics

  • Accuracy: The delay might not be precisely the number of seconds you specify. It could be slightly longer depending on the system's load and scheduling.
  • Thread Blocking: The time.sleep() function blocks the current thread. This means no other code within the same thread can execute during the delay.

Use Cases

You might use time.sleep() for these purposes:

  • Rate Limiting: When interacting with APIs, you can prevent overloading the server by adding a delay between requests.
  • Animations and Visual Effects: Introduce pauses to control the speed of animations or other visual changes.
  • Testing: Pause your code while inspecting results, variables, or other information to ensure correct operation.
  • User Experience: Create pauses to make console output easier to read or to introduce a short wait after a user input is received for various purposes.

Summary

The time.sleep() function from the time module is the fundamental method for adding delays in Python. It is a quick and easy method to pause the execution of your code for a specific amount of time. While using it, remember that it blocks the thread, which can impact more complex applications.