Search code examples
batch-fileoverridingcountdown

Override Countdown


When making Batch files, I still haven't learnt how to make a question override countdown. What I mean by this is, say you have an ask question sequence like this:

set /p LeavingQuestion1= 

if %LeavingQuestion1%==15 goto Question2

Is there a way which I can implement a countdown to this question so if they don't answer the question in 5 seconds, it goes to MainMenu.


Solution

  • Is the answer 1 character long? If so, you could do something like this:

    REM Asks for input. You might want to add on /N to hide the prompt.
    choice /c abcz /t 5 /d z
    
    REM Checks if the time ran out, otherwise goes to next question...
    if %errorlevel%==4 goto MainMenu ELSE goto question2
    

    Replace abcz with the possible choices. Each is 1 letter long. E.g. if you did abcz, it would ask for a, b, c, or z. Note that you might want to hide the z because that will be the answer that's automatically selected if you run out of time.

    The /t 5 /d z makes it select z if it waits more than 5 seconds.

    The way choice outputs is it makes %errorlevel% the number of the choice that was selected. So if it ran out of time, then z, the 4th answer, becomes %errorlevel%. This is why it checks for the errorlevel to be 4. Also, if you wanted to check for the first choice (in this case a), you could do if %errorlevel%==1, and if %errorlevel%==2 for the second choice (b), etc.

    Sorry if this was a bit confusing; do choice /? for some more info.