Search code examples
windowsbatch-filecmdtimeout

Timeout for user decision in windows batch file


I wrote a simple .bat file that asks the user a yes/ no question at one point. Now I want to add a timeout - lets say 10s - to it. Is there an easy way to do it?

My source so far:

SET /P ANSWER=Do you want it (Y/N)?
IF /i {%ANSWER%}=={y} GOTO :yes
IF /i {%ANSWER%}=={yes} GOTO :yes
GOTO :no

:yes
@echo Yeah, it will be done.
GOTO :continue

:no
@echo Nope, it will not happen.
GOTO :continue

:continue
@echo And on we go

Solution

  • This depends on version of windows your running. Different ones run different things.

    You can try some of the following:

    timeout 10
    
    ping 0.0.0.0 -n 1 -w 10000 > nul
    

    If those fail you could always go with a simple loop with choice (That is if choice works)

    :loop
    choice /t 10 /c ynr /cs /d r /m "Do you want it (Y/N)?"
    if errorlevel 3 goto :loop
    if errorlevel 2 goto :no
    if errorlevel 1 goto :yes
    
    :yes
    @echo Yeah, it will be done.
    GOTO :continue
    
    :no
    @echo Nope, it will not happen.
    GOTO :continue
    
    :continue
    @echo And on we go