you could always do

#do some stuff
print 'tasks done, now sleeping for 10 seconds'
for i in xrange(10,0,-1):
    time.sleep(1)
    print i

This snippet has the slightly annoying feature that each number gets printed out on a newline. To avoid this, you can

import sys
import time
for i in xrange(10,0,-1):
    sys.stdout.write(str(i)+' ')
    sys.stdout.flush()
    time.sleep(1)
Answer from aestrivex on Stack Overflow
🌐
Codecademy
codecademy.com › docs › python › time module › sleep()
Python | Time Module | sleep() | Codecademy
July 26, 2025 - This example shows how to use time.sleep() to create a countdown timer, demonstrating a practical, real-world application:
Discussions

python - How do I make a time delay? - Stack Overflow
Notice in recent Python versions (Python 3.4 or higher) you can use asyncio.sleep. It's related to asynchronous programming and asyncio. Check out next example: import asyncio from datetime import datetime @asyncio.coroutine def countdown(iteration_name, countdown_sec): """ Just count for some ... More on stackoverflow.com
🌐 stackoverflow.com
How do you have a countdown timer without it freezing your whole entire program until the whole loop is done?
Some of these recommendations are overkill for what you're trying to do. A simple Thread with some timing logic should suffice. In the example below, we create a thread which calls the timer function. This code will probably look like what you already had, the only difference is it is not blocking (i.e. you can do other things while the thread chugs along). I have simulated a simple game which will count to 15 (these are sample questions); in this simulation we assume each answer takes 1 second to answer (defined by the sleep). You'll notice that we never get to 15 because the timer runs out (it is defined as 10 seconds). from threading import Thread from time import sleep def timer(): sleep_duration = 10 while sleep_duration > 0: print(f"you have {sleep_duration} seconds left") sleep(1) sleep_duration -= 1 print("timer completed") def main(): timer_thread = Thread(target=timer) timer_thread.start() for i in range(0, 15): # check the timer if not timer_thread.is_alive(): # timer is complete print("oh no. you ran out of time!") break # game logic here print(f"answer question {i}") sleep(1) if __name__ == "__main__": main() More on reddit.com
🌐 r/learnpython
12
3
August 29, 2019
Countdown timer does not count down
I am trying to write a simple countdown timer and for some reason, when I run the script it hangs up and does nothing. # countdown one minute import time countdown = 60 while countdown > 0: print(str(countdown), end… More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
1
0
January 30, 2021
Countdown Timer in Python - Code Review Stack Exchange
I am a beginner in Python and I am yet to move on from the basics to things like OOP.I wrote all of this code (Python 3) in an hour or so for a simple countdown timer.Although some parts of it are More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
July 18, 2018
🌐
IONOS
ionos.com › digital guide › websites › web development › python sleep
How to pause programs with Python sleep
February 1, 2023 - Simply request the current time and output it in the format hour, minutes, seconds. Then set a delay of exactly one second and command the program to loop again using Python sleep.
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-create-a-countdown-timer-using-python
How To Create a Countdown Timer Using Python? - GeeksforGeeks
May 9, 2025 - Follow the below steps to create a countdown timer: ... Use divmod(t, 60) to convert seconds to minutes and seconds. Format the time string using '{:02d}:{:02d}'.format(mins, secs).
🌐
Real Python
realpython.com › python-sleep
Python sleep(): How to Add Time Delays to Your Code – Real Python
August 1, 2023 - In this tutorial, you'll learn how to add time delays to your Python programs. You'll use decorators and the built-in time module to add Python sleep() calls to your code. Then, you'll discover how time delays work with threads, asynchronous functions, and graphical user interfaces.
🌐
Mimo
mimo.org › glossary › python › time-sleep
Python time sleep: Pausing Code Execution in Python
Pause Python programs with time.sleep(). Learn to add delays for tasks, manage countdowns, limit API requests, and create smooth workflows.
Find elsewhere
🌐
CopyProgramming
copyprogramming.com › howto › display-a-countdown-for-the-python-sleep-function
Mastering Countdowns with Python's Sleep Function in 2026 - Mastering countdowns with pythons sleep function
February 9, 2026 - It blocks execution, so pairing it with a countdown loop provides real-time progress visibility without external libraries. In Python 3.14, time.sleep() remains unchanged in core behavior but benefits from free-threaded builds that reduce single-threaded performance penalties to 5-10%.
🌐
Programiz
programiz.com › python-programming › time › sleep
Python sleep() (With Examples)
import time while True: # get current local time as structured data current_time = time.localtime() # format the time in 12-hour clock with AM/PM formatted_time = time.strftime("%I:%M:%S %p", current_time) print(formatted_time) time.sleep(1) Output · 01:47:43 PM 01:47:44 PM 01:47:45 PM 01:47:46 PM ... ... ... In the above example, we obtain and print the current local time inside an infinite while loop. Then, the program waits for 1 second before repeating the same process. Also Read: Python Program to Create a Countdown Timer ·
🌐
StrataScratch
stratascratch.com › blog › python-sleep-function
How to Use Python’s Sleep Function - StrataScratch
October 14, 2025 - from time import sleep print("Bot: Hi there!") sleep(1.2) print("Bot: How can I help you today?") sleep(1.2) print("Bot: You can ask me about your balance, recent transactions, or support.") Here is the output after one second. Next, it outputs the question. Here is the entire output. This makes the interaction feel more natural and human-like. In real projects, you often deal with large amounts of data and slow operations. The Python sleep function helps simulate realistic timing and control flow across complex scripts.
🌐
Learn By Example
learnbyexample.org › python-time-sleep-method
Python time sleep() Method - Learn By Example
April 16, 2024 - Learn about Python's time.sleep() method: its usage, syntax, parameters, working, and examples including adding a delay, creating a countdown timer, simulating loading/progress, polling with timeout, and rate limiting requests.
🌐
Reddit
reddit.com › r/learnpython › how do you have a countdown timer without it freezing your whole entire program until the whole loop is done?
r/learnpython on Reddit: How do you have a countdown timer without it freezing your whole entire program until the whole loop is done?
August 29, 2019 -

I am semi-new to coding python. I know the ins and outs but this problem I cannot find a solution to anywhere. I am coding a personal quiz for my friends to take just for fun. I want to add a 10 minute timer to it so I have a function with a while loop that minuses 1 second from the timer. But whenever it goes to that part of the code, it will freeze until the timer hits 0 and then it continues. Is there a way around this or should I just scrap the timer idea? Thank you in advance!:)

🌐
Delft Stack
delftstack.com › home › howto › python › python countdown timer
How to Create a Countdown Timer in Python | Delft Stack
February 2, 2024 - The first thing to do is import the time module to use the sleep() function. ... Then declare a function to act as the countdown timer. Let’s call this function countdown(). The function will accept a single parameter: the number of seconds ...
🌐
freeCodeCamp
forum.freecodecamp.org › python
Countdown timer does not count down - Python - The freeCodeCamp Forum
January 30, 2021 - I am trying to write a simple countdown timer and for some reason, when I run the script it hangs up and does nothing. # countdown one minute import time countdown = 60 while countdown > 0: print(str(countdown), end=' ') countdown -= 1 time.sleep(1) The problem has something to do with the sleep function, although I’m not sure why.
Top answer
1 of 1
7

Before entering into the meat of the answer, let's talk about time accuracy for a bit.

For starter, time.sleep is not extremely accurate as it can be (a little bit) longer than the requested sleeping time. And even if it was, you’re performing work inbetween the repeated sleep calls, which take time and add up. So each cycle in the while loop of countdown_timer take more than a single second. Let's evaluate how much by using the following file:

import time
import datetime
import timeit


def countdown_timer(x):
    while x >= 0 :
        x -= 1
        print("{} remaining".format(str(datetime.timedelta(seconds=x))))
        print("\n")
        time.sleep(1)


if __name__ == '__main__':
    print(timeit.timeit(lambda:countdown_timer(120), number=1))

And the output is:

0:01:59 remaining


0:01:58 remaining

[Snip for readability]

0:00:01 remaining


0:00:00 remaining


-1 day, 23:59:59 remaining


121.14761522800109

Wow… That remaining time at the end… That's unexpected. Thing is that the way your while loop is setup, you are performing x + 1 iterations; which explains the 121 seconds your countdown take as well as that last remaining time. Just change the condition to while x > 0: and you’re good. But do you see that your counter drift of about 150ms over the course of two minutes? That will be 1 second and a half after 20 minutes, between 4 and 5 seconds on a 1 hour timer and several minutes for a 1 day timer…

You need to account for that drift. And the easiest way to do it is to maintain an ideal time to sleep up to which is 1 second in the future, and then compute the difference between the current time and this ideal time to try and sleep this exact amount of time. Luckily, this difference is easily computed using timedelta.total_seconds:

import time
import datetime
import timeit


def countdown_timer(x, now=datetime.datetime.now):
    target = now()
    one_second_later = datetime.timedelta(seconds=1)
    for remaining in range(x, 0, -1):
        target += one_second_later
        print(datetime.timedelta(seconds=remaining), 'remaining', end='\r')
        time.sleep((target - now()).total_seconds())
    print('\nTIMER ended')


if __name__ == '__main__':
    print(timeit.timeit(lambda:countdown_timer(120), number=1))

And the timing is way better:

0:00:00 remaining
TIMER ended
120.00124583899742

Just a single millisecond of drift. In fact, this drift is always compensated for and never accumulate. A run for 1200 seconds outputs:

0:00:00 remaining
TIMER ended
1200.0010585399978

Now for the rest of the code. Did you note how the calling code was under an if __name__ == '__main__': clause? You should get into this habit as it allows to more easily import and test the code you are developping. This will also hopefully force you to gather your code into functions and to make better usage of parameters and return values.

A coarse rewrite could look like:

import time
import datetime


def countdown_timer(x, now=datetime.datetime.now):
    target = now()
    one_second_later = datetime.timedelta(seconds=1)
    for remaining in range(x, 0, -1):
        target += one_second_later
        print(datetime.timedelta(seconds=remaining), 'remaining', end='\r')
        time.sleep((target - now()).total_seconds())
    print('\nTIMER ended')


def get_input_format(supported_formats=('hrs', 'min', 'sec')):
    while True:
        units = input('Enter the format in which you want to time yourself {}: '.format(supported_formats))
        if units in supported_formats:
            return units
        print('Invalid input. Please re-enter your desired format')
        print('The input is case sensitive')


def IOTimer(unit_input):
    while True:
        try:
            if unit_input == "hrs":
                hours = int(input("Enter the number of hours: "))
                print("\n")
                minutes = int(input("Enter the number of minutes: "))
                print("\n")
                seconds = int(input("Enter the number of seconds: "))
                print("\n")
                break
            elif unit_input == "min":
                hours = 0
                minutes = int(input("Enter the number of minutes: "))
                print("\n")
                seconds = int(input("Enter the number of seconds: "))
                print("\n")
                break
            elif unit_input == "sec":
                hours = 0
                minutes = 0
                seconds = int(input("Enter the number of seconds: "))
                print("\n")
                break
        except:
            print("Invalid Input. Re-enter the values")
            print("\n")
    hours_in_sec = hours*3600
    minutes_in_sec = minutes*60
    total_seconds = hours_in_sec + minutes_in_sec + seconds
    print("Starting countdown for {}".format(str(datetime.timedelta(seconds=total_seconds))))
    print("\n")
    time.sleep(2)
    countdown_timer(total_seconds)


if __name__ == '__main__':
    IOTimer(get_input_format())

But there is still improvement for the IOTimer function:

  • the name looks like it is a class as per PEP8, the official Python style guide, function names should be lower_snake_case;
  • I already removed the recursive call as it is already handled by the while True: loop;
  • there is a lot of repetitions in the various if statements;
  • you should not use a bare except statement, always specify the exceptions you’re expecting, otherwise it may create hard-to-diagnose bugs;
  • I hardly see a valid reason to sleep 2 seconds before starting the timer.

Revised version look like:

import time
import datetime


def countdown_timer(x, now=datetime.datetime.now):
    target = now()
    one_second_later = datetime.timedelta(seconds=1)
    for remaining in range(x, 0, -1):
        target += one_second_later
        print(datetime.timedelta(seconds=remaining), 'remaining', end='\r')
        time.sleep((target - now()).total_seconds())
    print('\nTIMER ended')


def get_input_format(supported_formats=('hrs', 'min', 'sec')):
    while True:
        units = input('Enter the format in which you want to time yourself {}: '.format(supported_formats))
        if units in supported_formats:
            return units
        print('Invalid input. Please re-enter your desired format')
        print('The input is case sensitive')


def main(unit_input):
    hours = minutes = seconds = 0
    while True:
        try:
            if unit_input == 'hrs':
                hours = int(input('Enter the number of hours: '))
            if unit_input != 'sec':
                minutes = int(input('Enter the number of minutes: '))
            seconds = int(input('Enter the number of seconds: '))
        except ValueError:
            print('Invalid Input. Re-enter the values')
        else:
            break
    delay = datetime.timedelta(hours=hours, minutes=minutes, seconds=seconds)
    print('Starting countdown for {}'.format(delay))
    countdown_timer(int(delay.total_seconds()))


if __name__ == '__main__':
    main(get_input_format())

But the whole point of these two extra functions is to only gather parameters for the script from the user. Let specialized modules do the work for you. Let me introduce you to argparse:

import time
import datetime
import argparse


def countdown_timer(x, now=datetime.datetime.now):
    target = now()
    one_second_later = datetime.timedelta(seconds=1)
    for remaining in range(x, 0, -1):
        target += one_second_later
        print(datetime.timedelta(seconds=remaining), 'remaining', end='\r')
        time.sleep((target - now()).total_seconds())
    print('\nTIMER ended')


def command_line_parser():
    parser = argparse.ArgumentParser(description='Simple countdown timer', conflict_handler='resolve')
    parser.add_argument('seconds', type=int, help='amount of seconds to wait for')
    parser.add_argument('-m', '--minutes', '--min', type=int, help='additional amount of minutes to wait for')
    parser.add_argument('-h', '--hours', type=int, help='additional amount of hours to wait for')
    return parser


if __name__ == '__main__':
    args = command_line_parser().parse_args()
    delay = datetime.timedelta(**vars(args))
    print('Starting countdown for', delay)
    countdown_timer(int(delay.total_seconds()))

Usage being:

$ python simple_timer.py -h 1 -m 23 45
🌐
Analytics Vidhya
analyticsvidhya.com › home › mastering the python time.sleep() function
Mastering the Python time.sleep() Function
January 19, 2024 - An advanced use case involves implementing timers and delays using time.sleep(). For instance, creating a countdown timer displaying remaining time after each second:
🌐
DigitalOcean
digitalocean.com › community › tutorials › python-time-sleep
Python time.sleep(): How to Pause Execution in Python Scripts | DigitalOcean
January 27, 2026 - The time.sleep() function is a synchronous operation that blocks the execution of the current thread for a specified amount of time. It is best suited for situations where a simple, predictable delay is required and blocking behavior is acceptable. ... Adding a fixed delay between repeated ...
🌐
MindMajix
mindmajix.com › blog › python › python sleep method
Sleep Method in Python
Welcome to Mindmajix Python Tutorial Print this message after a wait of 2.4 seconds · Example 2) Create a Simple countdown timer · import time seconds = 5 while seconds > 0: print(seconds) time.sleep(1) seconds = seconds - 1 · Output: 5 4 ...
🌐
Hackr
hackr.io › home › articles › programming › python
Python Sleep() Method | Docs With Examples
March 5, 2025 - ... You can use sleep() in combination with time.time() to implement a time limit. import time start_time = time.time() while time.time() - start_time < 10: print("Running...") time.sleep(2) # Pause execution every 2 seconds print("Time limit ...
🌐
Programiz
programiz.com › python-programming › examples › countdown-timer
Python Program to Create a Countdown Timer
Python time Module · import time def countdown(time_sec): while time_sec: mins, secs = divmod(time_sec, 60) timeformat = '{:02d}:{:02d}'.format(mins, secs) print(timeformat, end='\r') time.sleep(1) time_sec -= 1 print("stop") countdown(5) The divmod() method takes two numbers and returns a pair of numbers (a tuple) consisting of their quotient and remainder.