Implementing timed input in batch file. (countdown to a minute)

3.1k views Asked by At

I am using windows 8 to write a batch file and I got stuck in implementing the timer in batch file. I want to ask input from the user and give them one minute to type their input. Once the time hit a minute then display message like 'the time is over'. So, the time will start from 1 second and ends at 60 seconds OR start from 60 seconds and going down to 0 second. Either works just fine. Additionally, I want timer to be displayed somewhere on screen so that they can see the countdown. Also, while the timer is running I want the user to be able to type a word and hit enter. This program will not make user wait, but it will wait until the time is over OR as soon as the user enter a word (whichever comes first). After they enter a valid word then I want to store that word in certain variable and do something like (goto VALIDWORD OR echo That is a valid word!) I don't know if this is possible in batch file and there are more advanced language to use, but I want to complete this program using batch scripting. Thank you. Following is my concept:

@echo off
:Start
color EC
set /a time =60

:loop
cls
if %time% EQU 0 goto Timesup
if %time% LEQ 60 goto CONTINUE

:CONTINUE
ping localhost -n 2 >nul
set /a time-=1
set /p cho=     Enter your word: 
echo Remaing Time: %time%
goto loop

:Timesup
echo The time is over!
exit

Any ideas or support would be appreciated. Again Thanks!

1

There are 1 answers

7
Aacini On BEST ANSWER

Batch files are not designed for tasks like this one, but it is possible to perform certain advanced managements although in a limited manner. The subroutine below use choice command to get input keys, so it does not allow to end the input with Enter key nor to delete characters with BackSpace; it use 0 and 1 keys for such tasks.

@echo off
setlocal

call :ReadTimedInput 60 word=
echo Word read: "%word%"
goto :EOF


:ReadTimedInput seconds result=
setlocal EnableDelayedExpansion

set /A seconds=100+%1
set "letters=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
for /F %%a in ('copy /Z "%~F0" NUL') do set "CR=%%a"
for /F %%a in ('echo prompt $H ^| cmd') do set "BS=%%a"

echo Enter a word; press 0 to End, press 1 to Clear
:clear
set /P "=X!CR!                                     !CR!" < NUL
set "result="
:loop
   set /P "=X!BS! !CR!%seconds:~-2%: %result%" < NUL
   choice /C ¡10%letters% /N /CS /T 1 /D ¡ > NUL
   if %errorlevel% equ 1 goto tick
   if %errorlevel% equ 2 goto clear
   if %errorlevel% equ 3 echo/& goto endInput
   set /A char=%errorlevel%-4
   set "result=%result%!letters:~%char%,1!"
   :tick
   set /A seconds-=1
if %seconds% gtr 100 goto loop
echo !CR!00
set "result=Time out"
:endInput
endlocal & set "%2=%result%"
exit /B