Home > front end >  loop using batch until any key is pressed
loop using batch until any key is pressed

Time:03-25

I recently made this little code.

@echo off
mode 1000
set /A x=0
:loop
timeout /T 1 > Nul /nobreak
set /A x=x 1
echo %X%
goto loop

Can someone please help me and edit this code, that it loops, until any key is pressed and then stops the loop? Im new in coding using Batch and therefore dont know how to do it :(

CodePudding user response:

I think removing the /nobreak should help

CodePudding user response:

Awaiting a key press while other activities are ongoing is not that trivial in batch scripting.

However, here is a imperfect but quite simple semi-solution using choice and ErrorLevel:

@echo off
set /A "X=0"
:LOOP
rem /* `choice is utilised; all (case-insensitive) letter and numeral keys (excluding
rem    key `0`) are defined to quit the loop; `choice` features a timeout, upon which
rem    the default choice (key `0` here) is taken: */
choice /C abcdefghijklmnopqrstuvwxyz1234567890 /T 1 /D 0 > nul
rem /* `choice` reflects the actually pressed key in the `ErrorLevel` value, meaning
rem    `ErrorLevel = 1` reflects the first key `a`, and `ErrorLevel = 36` reflects
rem    the last one in the list, `0`; since the default choice after the timeout is
rem    `0`, pressing the `0` key has got the same effect as not pressing any key: */
if ErrorLevel 1 if not ErrorLevel 36 goto :QUIT
set /A "X =1"
echo %X%
goto :LOOP
:QUIT

CodePudding user response:

The choice approach (see Mofi's answer) was my first idea too, but it contradicts your "any key" demand.

Therefore I use a different approach: start another instance in the background, which just waits for a key (pause) and then creates a file.
The main loop exits, once the file exists.

@echo off 
setlocal
start /b cmd /c "pause >nul & break>flag"
del flag >nul 2>&1
:loop
if exist flag goto :done
timeout 1 >nul
set /a count =1
echo %count%
goto :loop
:done
del flag >nul 2>&1
echo interrupted by a key press.
  • Related