Batch countdown timer that doesn't clear rest of output?

放肆的年华 提交于 2020-03-02 06:31:59

问题


I am trying to create a batch timer that doesn't clear the output above it.

I have a timer function created, but am looking to improve it so that I can still view the output above it without having lines on lines of a countdown in the output. My current function is:

@echo off
echo KEEP THIS OUTPUT
CALL :timer 10
rem Do more things...
EXIT

:Timer
set time=%~1

:loop
cls

echo Countdown - [%time%]

set /a time=%time%-1
if %time%==0 goto timesup

ping localhost -n 2 > nul
goto loop

:timesup
echo Timer completed!!
EXIT /B 0

Currently, the timer clears the screen, but I would like to make it so that the output above this timer stays.

For example, at 10 seconds, the output should be:

KEEP THIS OUTPUT
Countdown - [10]

And then the output should change to:

KEEP THIS OUTPUT
Countdown - [9]

The output should NOT be:

KEEP THIS OUTPUT
Countdown - [10]
Countdown - [9]

and should NOT be:

Countdown - [9]

Is there any way to do this?


回答1:


It can be done with special characters, carriage return or backspace.

A carriage return moves the cursor back to the beginning of the line.
But to be on the same line as the Countdown text, you can't use the echo command, as it always appends an linefeed.
Instead I use the set /p command to avoid this.

@Echo off 
setlocal EnableDelayedExpansion
for /F %%# in ('copy /Z "%~dpf0" NUL') do set "CR=%%#"

for /L %%n in (10 -1 0) do (
    <nul set /p ".=Countdown[%%n] !CR!"
    ping localhost -n 2 > nul
)



回答2:


Another way to output any length strings repeatedly to the same line is using Ansi ESC sequences
(which are supported again in the console of Windows 10 >=Treshold2).

As some editors have problems creating/saving this to a batch file, certutil is used to create it.

:: Q:\Test\2019\05\27\SO_56330510.cmd
@echo off
if not defined ESC call :GetEsc
echo KEEP THIS OUTPUT
CALL :timer 10
rem Do more things...
EXIT /B

:Timer
Echo Countdown - [%1]
For /l %%L in (%1,-1,0) Do Echo %Ansi%Countdown - [%%L]&Timeout /t 1 >Nul
echo %Ansi%Timer completed!!
EXIT /B 0

:GetEsc just in case you can't create and save the ESC[ sequence in your editor
echo 1B 5B>ESC.hex
Del ESC.bin >NUL 2>&1
certutil -decodehex ESC.hex ESC.bin >NUL 2>&1
Set /P ESC=<ESC.bin
set "Ansi=%ESC%1F%ESC%0J"
Del ESC.* >NUL 2>&1


来源:https://stackoverflow.com/questions/56330510/batch-countdown-timer-that-doesnt-clear-rest-of-output

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!