How to display a countdown on a single line in the console?

  • 9 months ago
Comment

ChatGPT
1 / 1

You can display a countdown on a single line in the console by updating the content of the line as the countdown progresses. You can achieve this in various programming languages, but I'll provide examples in both Python and PowerShell.

Python Example:

python
import time
import sys

def countdown(seconds):
for i in range(seconds, 0, -1):
sys.stdout.write("\rCountdown: {:2d} seconds".format(i))
sys.stdout.flush()
time.sleep(1)
print("\rCountdown: Done! ")

countdown(10) # Replace 10 with the desired countdown duration

PowerShell Example:

powershell
function Countdown($seconds) {
for ($i = $seconds; $i -gt 0; $i--) {
Write-Host -NoNewline ("`rCountdown: {0} seconds" -f $i)
Start-Sleep -Seconds 1
}
Write-Host -NoNewline "`rCountdown: Done! "
}

Countdown 10 # Replace 10 with the desired countdown duration

Both of these examples use the carriage return character (\r) to move the cursor back to the beginning of the line and overwrite the previous content with the updated countdown value. The flush() method in Python and the -NoNewline parameter in PowerShell are used to ensure that the content is immediately displayed without waiting for a line break.

Replace the 10 with the desired countdown duration in seconds. Run the scripts in the respective environments to see the countdown displayed on a single line.