Reputation: 59
I need to print out countdown timer for the time my script sleeps.
Screen output looks like this -
Started Script Script will Sleep for 100 seconds Time left 100 Time left 99 Time left 98
I want print the Time left but by erasing the previous entry.
at time 0
Started Script Script will Sleep for 100 seconds Time left 100
at time 1
Started Script Script will Sleep for 100 seconds Time left 99
at time 2
Started Script Script will Sleep for 100 seconds Time left 98
How can I do this in tcl?
Upvotes: 1
Views: 1306
Reputation: 137807
The simplest way to do this is with some terminal tricks. The key trick is that printing a carriage return (\u000d
or \r
) sends the cursor back to the start of the current line.
puts "Started Script\n"
# Turn off output buffering; important!
fconfigure stdout -buffering none
puts "Script will sleep for 100 seconds\n"
set deadline [expr {[clock seconds] + 100}]
while 1 {
set now [clock seconds]
if {$deadline <= $now} {
break
}
# Tricky; the CR is critical to making this work...
puts -nonewline "\rTime left [expr {$deadline - $now}] "
# Sleep *half* a second for accuracy
after 500
}
# Blank the countdown line and put a finished message with a cheap hack
puts -nonewline "[string repeat " " 15]\rDone!"
You can get a more accurate countdown by using clock milliseconds
as your timing source and shortening the sleep in after
; you'll need some (small amount of) extra work to convert the time remaining to seconds in that case.
Upvotes: 2