Home > database >  Advance timer with batch script
Advance timer with batch script

Time:07-04

I want to make a timer with counts back wards and has three digits.

e.g.: (101, 100, 099, 098 . . . , 011, 010, 009, 008, . . . ,002, 001)

When the Timer comes to 099 it outputs 98 next instead of 098 and so on. e.g. : (98, 97, 96) instead of (098, 097, 096) the 0 literally vanishes from the output.

How can I fix this?

@ECHO OFF

MODE CON: COLS=60 LINES=20

COLOR 4

TITLE : [TIMER]

:START

CLS

set /a sec=103

:LOOP

IF %sec% == 99 (
GOTO OUT
) ELSE (
CLS
ECHO %sec%
timeout /t 1 /nobreak >nul
set /a sec-=1
GOTO LOOP
)

:OUT

IF %sec% == 9 (
GOTO OUT1
) ELSE (
CLS
ECHO 0%sec%
timeout /t 1 /nobreak >nul
set /a sec-=1
GOTO LOOP
)

:OUT1
 
IF %sec% == 0 (
GOTO OUT1
) ELSE (
CLS
ECHO 00%sec%
timeout /t 1 /nobreak >nul
set /a sec-=1
GOTO LOOP
)

CLS

ECHO ALL DONE

PAUSE > NUL

EXIT

CodePudding user response:

set has some substring processing. For example you can echo just the last <n> characters of a string. Using this makes your loop quite trivial. Just add 1000 to the start value and stop when it reaches 1000 instead of 0:

@echo off
setlocal

set sec=1103
:loop
echo %sec:~-3%
timeout /t 1 >nul
set /a sec-=1
if %sec% geq 1000 goto :loop
echo done

CodePudding user response:

And if you're using Windows 10 Build 18363 or later, you could have a little bit of fun by playing around with ANSI escape sequences.

For example, just save this as a .cmd file and double-click it to see what happens:

@Echo Off
SetLocal EnableExtensions DisableDelayedExpansion

For /F %%G In ('"Prompt $E & For %%H In (1) Do Rem"') Do Set "$E=%%G"
Echo Timer
For /L %%G In (1103 -1 1000) Do (
    Set /P "=%$E%[31m%%G%$E%[4D%$E%[1K%$E%[?25l" 0<NUL
    %SystemRoot%\System32\PATHPING.EXE 127.0.0.1 -n -q 1 -p 981 1>NUL
)
Echo(%$E%[?25h%$E%[0m& Pause
  • Related