Ad space (banner)
🐍Python Lessons
Lesson 57 / 69

Waiting for a Fixed Amount of Time (time.sleep)

This lesson covers pausing execution for a set amount of time with time.sleep(), so you can write programs that control timing. It's written for anyone searching "Python time.sleep usage".

time.sleep(seconds) pauses execution for the given number of seconds. It's useful whenever you want to space out API calls, or deliberately delay how a process proceeds. Unlike JavaScript's setTimeout, which needs a callback function, Python's simplicity lets you pause execution directly, right where you are.

The sample code prints "Starting" and then waits 0.5 seconds with time.sleep(0.5), before printing "Ran after 0.5 seconds." Try changing that 0.5 to a different value and see how the actual wait time changes.

A common beginner mistake is not realizing that time.sleep() completely blocks the whole program while it waits. If you want to wait for something while other work continues in parallel, you need a more advanced mechanism — asynchronous processing (asyncio). For a simple pause, sleep is fine, but which one you need depends on the situation.

Waiting a bit before retrying, to avoid overwhelming a server with requests, is a real-world scenario this technique often supports. It's also a foundational idea for programs that need to work with the passage of time — GUI apps, frame control in games, and more.

Python
OUTPUT

💡 The Python engine may take a few seconds to load the first time you run code.

Ad space (banner)
Ad space (in-article)