4

I actually wanted to create a timer using batch program and when I run the code the output is not the way I want. The screen continues flicking without decreasing the second. Can someone Help me. Thanks alot.

@echo off
set countdown=10
:loop
if %countdown% == 0 goto end
cls
echo %countdown% 
timeout /t 1 /NOBREAK
set/a count=%countdown%-1
goto loop
:end
cls
echo Time's up!
pause

2 Answers 2

2

You should replace this line set/a count=%countdown%-1 by this one set /a countdown=countdown-1 or by a shortened set /a countdown-=1.

@echo off
set "countdown=10"
:loop
if "%countdown%" EQU "0" goto end
cls
echo %countdown% 
set /a countdown-=1
timeout /t 1 /NOBREAK>nul
goto loop
:end
cls
echo Time's up!
pause
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks so much, it's working. And why it has this sign " on set/a "countdown=10"
1

A way to do it without the goto / label

@echo off
Set count=10
Setlocal enableDelayedExpansion
For /L %%a in (1,1,!count!) DO (
    Set /a count=!count! - 1
    (ECHO <esc>[1;1H<esc>[K!count!)
    (
        TIMEOUT 1 >nul
    )
)

ECHO times up!    
pause

<esc>[1;1H<esc>[K Sets the position of the text (line;column) and clears the line from that point. <esc> represents the ANSI escape character.
Using the ANSI cursor positioning allows you to refresh text on screen selectively, without having to clear the whole screen.

3 Comments

Just to mention, that you may need the latest version of Windows 10, for console Virtual Terminal sequences.
Ansi Sequences are Supported by all versions of Windows 10 - amendment - after reviewing, The Cursor Positioning System is indeed NOT ansi.
To clarify, my point is that the OP did not specify their OS version, simply Windows, therefore I felt it worth mentioning that cmd.exe by default will be unable to do this, unless the OP is using the latest OS.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.