-
Use
/WAIT
to Wait for the Command to Finish Execution in Batch Script -
Use the
TIMEOUT
Command to Delay the Execution in Batch Script -
Use the
PAUSE
Command to Pause the Execution in Batch Script -
Use the
CALL
Command to Wait for the Command to Finish Execution in Batch Script -
Use the
&&
Operator to Wait for Command to Finish Execution in Batch Script -
Use a Loop to Wait for Command to Finish Execution in Batch Script
-
Conclusion
Batch scripting in Windows allows users to automate tasks by writing a series of commands that the system can execute. Often, it’s crucial to ensure that a command finishes its execution before moving on to the next one.
There are multiple commands and installation processes in a Batch file that usually take some time to complete. But when a Batch file is run, it does not wait for a command process to finish; it executes all commands line by line.
It is important to make those commands wait for them to finish and then execute the next commands. For a process to wait until it is finished, we use the /wait
parameter with the START
command.
Instead of starting a command, if there is a need to insert delays in the Batch file for some time interval, we can use commands such as TIMEOUT
and PAUSE
to stop the execution of the next process for a short interval of time or until a key is pressed.
This tutorial illustrates different ways to wait for a command or a program to finish before executing the next command in the Windows Batch file.
Use /WAIT
to Wait for the Command to Finish Execution in Batch Script
The /WAIT
parameter is used with the START
command in a Batch file. It instructs the command prompt to wait for the command or application to complete its execution before moving on to the next line in the Batch script.
This parameter is particularly useful when you need to launch an application or script and ensure it finishes before proceeding.
The syntax of the START
command with the /WAIT
parameter is as follows:
START "title" [/D path] [/I] [/MIN] [/MAX] [/SEPARATE | /SHARED]
[/LOW | /NORMAL | /HIGH | /REALTIME | /ABOVENORMAL | /BELOWNORMAL]
[/AFFINITY <hex affinity>] [/WAIT] [/B] [command/program]
[parameters]
/WAIT
: This is the parameter we’re focusing on in this guide. It causes theSTART
command to wait for the executed command or program to finish before proceeding with the Batch script.
When we start a program in a Batch file using the START
command, we can wait until the program is finished by adding /wait
to the START
command. Even if there are multiple commands, /wait
can be used for each process to finish and move to the next one.
Also, the parameter /B
is used to stay in the same process without creating a new window. The START
command without the /B
parameter opens the program or command in a new window.
Wait for a Command to Finish Execution
For example, we need to wait for a command to finish execution before running the next one.
@echo off
echo starting first program.
START /B /WAIT cmd /c "C:\Users\Aastha Gas Harda\Desktop\testfile1.bat" > output.txt
echo The first program is executed successfully.
START /B systeminfo >> stdout.txt
echo All the programs are executed successfully
cmd /k
This Batch script executes two programs sequentially. It starts by running testfile1.bat
and waits for it to finish before echoing a success message.
Then, it gathers system information using systeminfo
and appends the output to output.txt
. Finally, it opens a new command prompt window for further interaction.
Output:
Wait for the .exe
File to Finish Execution
Another example is where we need to run a .exe
file and wait until the execution is done completely.
@echo off
echo starting first program.
START /B /WAIT JRuler.exe
echo The first program is executed successfully.
START /B systeminfo >> output.txt
echo All the programs are executed successfully
cmd /k
This Batch script first runs an application called JRuler.exe
and waits for it to finish. It then echoes a success message.
Next, it gathers system information using the systeminfo
command and appends the output to a file called output.txt
. Finally, it opens a new command prompt window for further interaction.
Output:
As soon as you close the .exe
file, the second program will begin execution. cmd /k
in the last line is used to prevent the command prompt from exiting after execution.
If there are multiple programs, you can use /WAIT
with each command to wait until the execution is finished. The START
command with the /WAIT
parameter doesn’t have any timeout, i.e., it does not matter how long the process will take to finish; it will wait until the process is completed.
@echo off
START /WAIT install1.exe
START /WAIT install2.exe
/WAIT
can only be used with the START
command. We can insert a time delay for other commands by using the TIMEOUT
and PAUSE
commands.
Use the TIMEOUT
Command to Delay the Execution in Batch Script
The TIMEOUT
command is used in Batch scripts to introduce a delay in the execution. It allows you to pause the script for a specified amount of time, measured in seconds.
This is particularly useful when you need to ensure that a process or task is completed before moving on to the next step.
The range for the TIMEOUT
command varies between -1
and 100000
. If the delay is set to -1
, it will act as a pause
command to wait until a key is pressed.
As in the previous method, we can replace the /wait
by inserting the TIMEOUT
command with the /t
parameter. The syntax for the TIMEOUT
command is given below:
TIMEOUT [/T timeout] [/NOBREAK]
/T timeout
: This option specifies the delay time in seconds. If omitted, the default delay is10
seconds./NOBREAK
: This option allows users to interrupt the countdown by pressing any key. If omitted, the countdown cannot be interrupted.
Let’s take the example in the previous method and add a time delay of 30
seconds after the execution of the first program.
@echo off
echo starting first program.
START /B JRuler.exe
TIMEOUT /t 30
echo The first program is executed successfully.
START /B systeminfo >> output.txt
echo All the programs are executed successfully
cmd /k
This Batch script automates the execution of two programs. It starts with JRuler.exe
and waits for 30
seconds.
Afterward, it echoes a success message. Then, it runs the systeminfo
command and appends the output to output.txt
.
Finally, it opens a new command prompt window for further interaction.
Output:
After 30
seconds, the second program will begin execution. Also, if a user presses a key before the timeout, the second program will begin execution.
To prevent user keystrokes, use the /nobreak
parameter with the TIMEOUT
command. This will ignore any key presses by the user.
However, you can stop the delay by pressing the Ctrl+C, which will raise the errorlevel1
.
Use the PAUSE
Command to Pause the Execution in Batch Script
The PAUSE
command in Batch scripting serves as a mechanism to temporarily halt the execution of a script. It displays the message "Press any key to continue..."
and waits for user input.
This is especially useful when you want to give users an opportunity to review information or confirm an action before proceeding with the script.
The PAUSE
command is simple and does not require any additional parameters or options. It is used as follows:
When the PAUSE
command is encountered in a Batch script, it prompts the user to press any key. Once a key is pressed, the script continues its execution.
The PAUSE
command is used to pause the execution of a Batch file until a key is pressed. It is useful if the user wants to read the output text or wait until a process is finished.
However, there is no timeout, and it will only continue until the user presses a key.
@echo off
echo starting first program.
START /B cmd /c "C:\Users\Aastha Gas Harda\Desktop\testfile1.bat" > output.txt
echo The first program is executed successfully.
PAUSE
START /B systeminfo >> output.txt
echo All the programs are executed successfully
cmd /k
This Batch script automates the execution of two programs. It starts with testfile1.bat
, captures its output to output.txt
, and confirms successful execution.
The script then prompts the user to press a key to continue. Next, it runs the systeminfo
command and appends its output to output.txt
.
Finally, it opens a new command prompt window for further interaction.
Output:
All the methods mentioned above work fine. If you use the START
command, it is recommended to use /wait
instead of delay commands as the process may take longer than specified.
Use the CALL
Command to Wait for the Command to Finish Execution in Batch Script
The CALL
command in Batch scripting is used to run another Batch file within the current script.
It essentially creates a temporary subroutine, allowing the original script to wait for the called script’s completion before proceeding. This makes it an effective method for synchronizing the execution of commands.
The syntax of the CALL
command is as follows:
CALL :label arguments
CALL [drive:][path]filename [arguments]
:label arguments
: This form is used to call a subroutine within the same Batch file, identified by a label.[drive:][path]filename [arguments]
: This form is used to call an external Batch file by specifying its full path along with any required arguments.
Let’s explore practical examples to demonstrate the use of the CALL
command.
Calling a Subroutine within the Same Batch File
@echo off
echo Starting Process I
CALL :ProcessI
echo Process I completed.
pause
exit
:ProcessI
echo Performing Process I...
:: Add your commands for Process I here
:: For example, "ping -n 5 127.0.0.1" simulates a delay
ping -n 5 127.0.0.1
exit /b
- In this script, we have a main section and a subroutine (
:ProcessI
). - The
CALL :ProcessI
command invokes the subroutine. The execution of the main Batch file will pause until:ProcessI
completes. - The
exit /b
command at the end of:ProcessI
is used to return to the main Batch file after completion.
Output:
Calling an External Batch File
This script uses CALL
to execute an external Batch file named testfile2.bat
located on the desktop.
@echo off
echo Starting Process J
CALL "C:\Users\Username\Desktop\testfile2.bat"
echo Process J completed.
pause
exit
This script automates the execution of an external Batch file, captures its output, and provides feedback along the way. The user is prompted to press a key to continue after the program finishes.
Output:
Use the &&
Operator to Wait for Command to Finish Execution in Batch Script
The &&
operator in Batch scripting allows you to execute commands sequentially, where the second command only runs if the first one succeeds. This creates a dependency between the commands, ensuring that they execute in a specific order.
The syntax of the &&
operator is as follows:
command1
: This is the first command that is executed.command2
: This is the second command that is only executed ifcommand1
succeeds (returns a zero exit code).
Let’s explore practical examples to demonstrate the use of the &&
operator.
Example 1: Running Commands Sequentially
@echo off
echo Starting Process K
echo Performing Process K... && ping -n 5 127.0.0.1
echo Process K completed successfully.
pause
exit
- In this script, the
echo Performing Process K...
command is followed by&&
, which means the next command (ping
) will only execute if the first command is successful. - The
ping
command simulates a delay by waiting for5
seconds (-n 5
) on the local machine (127.0.0.1
). - The script then echoes a message indicating successful completion.
Output:
Example 2: Using Conditional Execution with Batch Files
@echo off
echo Starting Process L
call :ProcessL && (
echo Process L completed successfully.
) || (
echo Process L encountered an error.
)
pause
exit
:ProcessL
echo Performing Process L...
:: Add your commands for Process L here
:: For example, "dir" lists files in the current directory
dir
exit /b
- In this script, the
call :ProcessL
command is followed by&&
. - The subsequent block of code within the
(
and)
is executed only if thecall :ProcessL
succeeds (returns a zero exit code). - If the
call :ProcessL
returns a non-zero exit code, the code after||
is executed instead. - This demonstrates how to conditionally execute different blocks of code based on the success of a preceding command.
Output:
Use a Loop to Wait for Command to Finish Execution in Batch Script
In Batch scripting, a loop is a control structure that allows a set of commands to be executed repeatedly. By utilizing a loop, you can continuously check the status of a process until it completes.
This approach is particularly useful for scenarios where you need to wait for a specific task to finish before proceeding.
Let’s delve into a practical example to demonstrate how to use a loop to wait for a command to complete.
@echo off
echo Starting Process K
echo Performing Process K...
:CheckProcess
tasklist | find /i "process_name.exe" >nul
if %errorlevel% neq 0 (
timeout /t 2 >nul
goto :CheckProcess
)
echo Process K completed successfully.
pause
exit
The Batch script begins with turning off command echoing using @echo off
. It echoes a message indicating the start of a process (Process K
).
Then, the :CheckProcess
label marks the start of a loop. This is where the script checks the status of the target process.
tasklist | find /i "process_name.exe" >nul
retrieves a list of running processes and searches for a process with the specified name (replace process_name.exe
with the actual process name). The >nul
part suppresses the output.
Next, the if %errorlevel% neq 0
checks the return code of the previous command. If it’s not equal to 0
(indicating that the process is still running), the loop continues.
timeout /t 2 >nul
introduces a 2
second delay using the timeout
command. The goto :CheckProcess
redirects the script back to the :CheckProcess
label, effectively creating a loop.
Once the process is no longer found, the script proceeds. Finally, it echoes a message confirming the successful completion of Process K
and waits for user confirmation before exiting.
Output:
Conclusion
This tutorial explores various methods to wait for a command to finish execution in Windows Batch scripting.
- Using
/WAIT
withSTART
: This method ensures the script waits for a command or application to complete using the/WAIT
parameter with theSTART
command. It’s ideal for launching applications that need to finish their tasks. - Introducing Delays with
TIMEOUT
: TheTIMEOUT
command allows for a specified delay in script execution. This is helpful when you want to provide a process with enough time to complete. - Temporary Halt with
PAUSE
: ThePAUSE
command temporarily stops script execution and prompts the user to press a key before continuing. This is useful for user interaction and confirmation. - Using
CALL
for Script Synchronization: TheCALL
command enables the execution of another Batch file within the current script, creating a temporary subroutine. This allows the original script to wait for the called script’s completion. - Conditional Execution with
&&
: The&&
operator ensures that the second command only runs if the first one succeeds, establishing a dependency between commands. This is useful for sequential execution. - Implementing Loops for Continuous Checking: A loop is a control structure that repeatedly checks the status of a process until it completes. This is valuable for scenarios where you need to wait for a specific task to finish.
By understanding these methods, you have gained a comprehensive toolkit for handling command execution and synchronization in Windows Batch scripting. These techniques are invaluable for automating various tasks efficiently.
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
The `wait` command in CMD is often used in batch scripts to pause the execution of the script for a specified amount of time.
Here’s an example of a simple batch script that uses `timeout` to create a wait time:
@echo off
echo Waiting for 5 seconds...
timeout /t 5
echo Done waiting!
What is the `wait` Command?
The `wait` command in CMD is a powerful utility that allows users to introduce a delay in the execution of commands or scripts. This command is essential for scenarios where timing is crucial, such as when waiting for a process to finish or allowing time for an operation to stabilize.
Mastering Git-Cmd: Your Quick Start Guide
How to Use the `wait` Command
Syntax Overview
The basic syntax of the `wait` command is:
wait [duration]
- `duration` specifies the time to wait before the command continues. It can be expressed in seconds or milliseconds, depending on your needs.
Basic Example of the `wait` Command
Here’s a simple example that showcases the `wait` command in action:
echo Starting Process...
wait 5
echo Process Resumed!
In this example, the first line prints “Starting Process…”. The command then pauses execution for 5 seconds due to the `wait` command, after which it resumes and prints “Process Resumed!”. This illustrates how you can create pauses in between commands for better readability and timing in your scripts.
Master Win Cmd: Your Quick Start Guide to Commands
Practical Applications of the `wait` Command
Delaying Batch File Execution
The `wait` command is particularly useful when creating batch files where order of operations and timing matter. For example, you might need to pause between steps in a process. Consider this batch file:
@echo off
echo Step 1: Initializing...
wait 10
echo Step 2: Processing...
wait 5
echo Step 3: Complete.
In this script:
- Step 1 initializes a process, followed by a 10-second wait.
- Step 2 proceeds after the wait, indicating to the user that something is occurring.
- After another 5-second wait, Step 3 confirms completion.
Each step adds clarity to what the script is doing in real-time.
Working with Scripts that Require Time Gaps
There are scenarios where scripts must wait for certain services or applications to be ready. For instance, if you are starting a service, ensuring it is fully operational before proceeding can prevent errors:
@echo off
net start "ServiceName"
wait 30
if errorlevel 1 (
echo Failed to start the service.
) else (
echo Service started successfully.
)
In this example:
- The script attempts to start a service named «ServiceName».
- It then uses the `wait` command to pause for 30 seconds, allowing the service time to initialize.
- After the wait, it checks if the service started successfully, providing feedback based on the result.
Mastering Wget Cmd: A Quick Guide to Downloads
Common Mistakes When Using `wait`
Forgetting to Specify Duration
One of the most common mistakes users make is omitting the duration. Failing to specify how long to wait can lead to circumstances where the script runs without any effective pauses, often resulting in processes overlapping or commands being executed out of order.
Misunderstanding Time Formats
Another common misunderstanding arises from time formats. Users might assume that the command accepts multiple time formats. However, if you enter an unsupported time format, CMD will raise an error. Always check your entry to ensure it matches the expected duration format to avoid execution issues.
Mastering Bat Cmd: Quick Tips for Command Line Success
Alternative Commands to `wait` in CMD
Using `timeout`
The `timeout` command is a popular alternative to `wait`. It has a similar purpose, with a slightly different interface. The syntax is as follows:
timeout [duration]
For example, using `timeout`:
echo Pausing for 10 seconds...
timeout 10
echo Resuming now.
This command pauses execution for 10 seconds and then resumes, providing a similar delay effect as `wait`.
Combining Commands for More Control
You can also manage the execution of external programs using the `start /wait` command. This combination allows you to launch an application and wait for it to complete before moving forward.
Here is an example:
start /wait myprogram.exe
echo Program has completed execution.
In this command, `myprogram.exe` is started, and the script automatically halts until this program finishes running. This approach is valuable when automating workflows that require the completion of specific applications before proceeding to the next step.
What Cmd: A Quick Guide to Cmd Commands
Summary of Key Points
The `wait` command is a critical tool for creating effective and organized CMD scripts. It introduces necessary pauses, enhances script clarity, and ensures that operations have time to complete, especially during automation.
Start Cmd: Your Quick Guide to Command Basics
Conclusion: Elevate Your CMD Skills
Practicing the `wait` command will significantly improve your CMD scripting skills and overall productivity. Mastering this command, along with understanding its alternatives, will equip you to handle time-sensitive operations efficiently. Continue exploring tutorials and resources to further enhance your CMD capabilities.
Mastering Netstat Cmd: Quick Tips for Network Analysis
Additional Resources
Documentation and References
For comprehensive details on the `wait` command and other CMD functionality, refer to the official Microsoft CMD documentation. Engaging with online forums and communities can also provide practical insights and tips from experienced users.
`wait` Command Related Articles
Consider reading additional articles on advanced CMD techniques for an even deeper understanding of CMD commands and scripting strategies, enabling you to harness the full potential of your CMD skills.
Download Article
Download Article
If you need some extra time for a command in your batch file to execute, there are several easy ways to delay a batch file. While the well-known sleep command from older versions of Windows is not available in Windows 10 or 11, you can use the timeout, pause, ping, and choice commands to wait a specific number of seconds or simply pause until the user presses a key. This wikiHow article will teach you 5 simple ways to delay the next command in your batch file on any version of Windows.
Things You Should Know
- The timeout command lets you pause for specific number of seconds, until a user presses a key, or indefinitely.
- Use the pause command to delay the batch file until a user presses any key, or the choice command to give the user options to choose from.
- You can hide on-screen messages that indicate delay to the user by adding >nul to the end of the timeout, ping, and choice commands.
-
By inserting the timeout command into your batch file, you can prompt the batch file to wait a specified number of seconds (or for a key press) before proceeding.[1]
This command is available on all modern versions of windows, including Windows 10.-
timeout /t <timeoutinseconds> [/nobreak].[2]
- To pause for 30 seconds and prevent the user from interrupting the pause with a keystroke, you’d enter timeout /t 30 /nobreak.[3]
- The user will see Waiting for 30 seconds, press CTRL+C to quit …
- To delay 100 seconds and allow the user to interrupt the delay, you’d use timeout /t 100.
- The user will see Waiting for 100 seconds, press a key to continue …
- To delay indefinitely until a user enters a keystroke, use timeout /t -1.
- The user will see Press any key to continue …
- If you don’t want to display a message to the user during the delay, add >nul to the end of your timeout command.
-
timeout /t <timeoutinseconds> [/nobreak].[2]
Advertisement
-
This simple command doesn’t require any flags and you can place it anywhere in your script to prevent further action. When the pause command runs in the batch file, the user will see Press any key to continue . . . on a new line. When the user presses a key, the script continues.[4]
- You might use pause right before a section of the batch file that you might not want to process, or before providing instructions to the user to insert a disk before continuing.[5]
- At the pause, you can stop the batch program completely by pressing Ctrl + C and then Y.
- You might use pause right before a section of the batch file that you might not want to process, or before providing instructions to the user to insert a disk before continuing.[5]
-
You can add a ping anywhere in your batch file, enter any hostname or IP address (including a nonexistent address), and specify the time in milliseconds to delay the next command. You’ll also be able to hide the output of the ping so the user won’t see what’s happening in the background.[6]
-
ping /n 1 /w <timeout in milliseconds> localhost >nul
- Ping has many more available flags, but for the purpose of delaying a batch file, you’ll only need to use a few. In this case, we’ll ping ourselves by using localhost as our destination.
- To pause quietly for 10 seconds, you’d use ping /n 1 /w 10000 localhost >nul
-
ping /n 1 /w <timeout in milliseconds> localhost >nul
Advertisement
-
You can customize the list of choices, use the default options of Y or N, or choose not to display any choices at all and simply delay your script for a specific period of time.[7]
-
choice [/c [<choice1><choice2><…>]] [/n] [/cs] [/t <seconds> /d <choice>] [/m <text>]
- /c <choice1><choice2><…>: Specifies the choices you’d like to create, which can include a-z, A-Z, 0-9, and ASCII characters 128-254.
- /t <seconds>: Use this flag to specify how many seconds to wait before the default choice is selected. You can set this value to any number between 0 (which instantly selects the default choice) and 9999.
- /d <choice>: Specifies the default choice from the list of choices created with /c.
- /n (optional): hides the list of choices, but still allows the user to select one.
- /m <text> (optional): displays a message before the choice list. If you don’t include this flag but don’t hide the choice list, the choices will still be displayed.
- /cs (optional): This specifies that choices are case-sensitive, which is important if you want to assign different functions to capital and lowercase letters.
- To create a delay with CHOICE without displaying a message or forcing the user to choose something, use rem | choice /c:AB /T:A,30 >nul. This command simply delays the batch file for 30 seconds (similar to using Timeout with no message), provides no choices to the user, and continues after the delay. You can replace 30 with any value up to 9999 (in seconds).
-
choice [/c [<choice1><choice2><…>]] [/n] [/cs] [/t <seconds> /d <choice>] [/m <text>]
-
If you’re using Windows XP or earlier, you can use sleep to specify a wait time in seconds. This command will not work in any newer versions of Windows starting with Windows Vista, but is the easiest way to add wait time to batch files running on older systems.
- sleep <seconds>
- The sleep command only requires the number of seconds you want to delay the batch file. For example, to wait 30 seconds before continuing, you’d use sleep 30.
Advertisement
Add New Question
-
Question
How do I not get a message when I use timeout?
Add the >nul qualifier, like this: timeout /t 120 >nul. This causes a 2 minute delay with no output to the screen.
-
Question
What if the sleep command doesn’t work?
If the sleep command doesn’t work, use timeout instead.
-
Question
What if I want to wait less than one second? I can’t just use a dot or a comma.
You can use the ping command. This command, if used with a non-existent IP address, will try to talk to a non-existent computer and give up after a specified number of milliseconds. Just multiply the number of seconds by 1000, and you’re good to go.
See more answers
Ask a Question
200 characters left
Include your email address to get a message when this question is answered.
Submit
Advertisement
-
You can run a batch file on any Windows computer by double-clicking it, or launch it from the command prompt.
-
The «PAUSE» command is best used in situations where you’re relying on a user to trigger the next section of the batch file, while the «TIMEOUT» command is suited to situations in which you want to allow the file to run automatically.
-
The formerly used «SLEEP» command does not work on Windows Vista or later, including Windows 10 and 11.
Thanks for submitting a tip for review!
Advertisement
About This Article
Thanks to all authors for creating a page that has been read 1,610,619 times.
Is this article up to date?
WAIT
To make a batch file wait for a number of seconds there
are several options available:
- PAUSE
- SLEEP
- TIMEOUT
- PING
- NETSH (Windows XP/Server 2003 only)
- CHOICE
- CountDown
- SystemTrayMessage
- Other scripting languages
- Unix ports
Note: | Click a script file name to expand and view its source code; click the file name again, or the expanded source code, to hide the source code again. To view the source code on its own, right-click the file name and choose Open or Open in separate tab or window. |
PAUSE
The most obvious way to pause a batch file is of course the PAUSE
command.
This will stop execution of the batch file until someone presses «any key».
Well, almost any key: Ctrl, Shift, NumLock etc. won’t work.
This is fine for interactive use, but sometimes we just want to delay the batch file for a fixed number of seconds, without user interaction.
SLEEP
SLEEP
was included in some of the Windows Resource Kits.
It waits for the specified number of seconds and then exits.
SLEEP 10
will delay execution of the next command by 10 seconds.
There are lots of SLEEP
clones available, including the ones mentioned in the UNIX Ports paragraph at the end of this page.
TIMEOUT
TIMEOUT
was included in some of the Windows Resource Kits, but is a standard command as of Windows 7.
It waits for the specified number of seconds or a keypress, and then exits.
So, unlike SLEEP
, TIMEOUT
‘s delay can be «bypassed» by pressing a key.
TIMEOUT 10
or
TIMEOUT /T 10
will delay execution of the next command by 10 seconds, or until a key is pressed, whichever is shorter.
D:\>TIMEOUT /T 10 Waiting for 10 seconds, press a key to continue ...
You may not always want to abort the delay with a simple key press, in which case you can use TIMEOUT
‘s optional /NOBREAK
switch:
D:\>TIMEOUT /T 10 /NOBREAK Waiting for 10 seconds, press CTRL+C to quit ...
You can still abort the delay, but this requires Ctrl+C instead of just any key, and will raise an ErrorLevel 1.
PING
For any MS-DOS or Windows version with a TCP/IP client, PING
can be used to delay execution for a number of seconds.
PING localhost -n 6 >NUL
will delay execution of the next command for (a little over) 5 seconds seconds (default interval between pings is 1 second, the last ping will add only a minimal number of milliseconds to the delay).
So always specify the number of seconds + 1 for the delay.
The PING
time-out technique is demonstrated in the following examples:
PMSleep.bat for Windows NT
-
@ECHO OFF
-
:: Check Windows version
-
IF NOT "%OS%"=="Windows_NT" GOTO Syntax
-
-
:: Check if a valid timeout period is specified
-
IF "%~1"=="" GOTO Syntax
-
IF NOT "%~2"=="" GOTO Syntax
-
ECHO.%*| FINDSTR /R /X /C:"[0-9][0-9]*" >NUL || GOTO Syntax
-
IF %~1 LSS 1 GOTO Syntax
-
IF %~1 GTR 3600 GOTO Syntax
-
-
:: Use local variable
-
SETLOCAL
-
-
:: Add 1 second for IPv4
-
SET /A seconds = %1 + 1
-
-
:: The actual command: try IPv4 first, if that fails try IPv6
-
PING -n %seconds% 127.0.0.1 >NUL 2>&1 || PING -n %1 ::1 >NUL 2>&1
-
-
:: Done
-
ENDLOCAL
-
GOTO:EOF
-
-
-
:Syntax
-
ECHO.
-
ECHO PMSleep.bat
-
ECHO Poor Man's SLEEP utility, Version 3.00 for Windows NT 4 and later.
-
ECHO Wait for a specified number of seconds.
-
ECHO.
-
ECHO Usage: CALL PMSLEEP seconds
-
ECHO.
-
ECHO Where: seconds is the number of seconds to wait (1..3600)
-
ECHO.
-
ECHO Notes: The script uses PING for the delay, so an IP stack is required.
-
ECHO The delay time will not be very accurate.
-
ECHO.
-
ECHO Written by Rob van der Woude
-
ECHO http://www.robvanderwoude.com
-
-
IF "%OS%"=="Windows_NT" EXIT /B 1
-
PMSlpW9x.bat for Windows 95/98
-
@ECHO OFF
-
:: Check if a timeout period is specified
-
IF "%1"=="" GOTO Syntax
-
-
:: Filter out slashes, they make the IF command crash
-
ECHO.%1 | FIND "/" >NUL
-
IF NOT ERRORLEVEL 1 GOTO Syntax
-
-
:: Check for a non-existent IP address
-
:: Note: this causes a small extra delay!
-
IF "%NonExist%"=="" SET NonExist=10.255.255.254
-
PING %NonExist% -n 1 -w 100 | FIND "TTL=" >NUL
-
IF ERRORLEVEL 1 GOTO Delay
-
SET NonExist=1.1.1.1
-
PING %NonExist% -n 1 -w 100 | FIND "TTL=" >NUL
-
IF NOT ERRORLEVEL 1 GOTO NoNonExist
-
-
:Delay
-
:: Use PING time-outs to create the delay
-
PING %NonExist% -n 1 -w %1000 >NUL
-
-
:: Show online help on errors
-
IF ERRORLEVEL 1 GOTO Syntax
-
-
:: Done
-
GOTO End
-
-
:NoNonExist
-
ECHO.
-
ECHO This batch file needs an invalid IP address to function
-
ECHO correctly.
-
ECHO Please specify an invalid IP address in an environment
-
ECHO variable named NonExist and run this batch file again.
-
-
:Syntax
-
ECHO.
-
ECHO PMSlpW9x.bat
-
ECHO Poor Man's SLEEP utility, Version 2.10 for Windows 95 / 98
-
ECHO Wait for a specified number of seconds.
-
ECHO.
-
ECHO Written by Rob van der Woude
-
ECHO http://www.robvanderwoude.com
-
ECHO Corrected and improved by Todd Renzema and Greg Hassler
-
ECHO.
-
ECHO Usage: CALL PMSLPW9X nn
-
ECHO.
-
ECHO Where: nn is the number of seconds to wait
-
ECHO.
-
ECHO Example: CALL PMSLPW9X 10
-
ECHO will wait for 10 seconds
-
ECHO.
-
ECHO Note: Due to "overhead" the actual delay may
-
ECHO prove to be up to a second longer
-
-
:End
-
💾 Download the PMSleep sources
NETSH
NETSH
may seem an unlikely choice to generate delays, but it is actually much like using PING
:
NETSH Diag Ping Loopback
will ping localhost, which takes about 5 seconds — hence a 5 seconds delay.
NETSH
is native in Windows XP Professional and later versions.
Unfortunately however, this trick will only work in Windows XP/Server 2003.
CHOICE
In MS-DOS 6, Windows 9*/ME and NT 4
REM | CHOICE /C:AB /T:A,10 >NUL
will add a 10 seconds delay.
By using REM |
before the CHOICE command, the standard input to CHOICE is blocked, so the only «way out» for CHOICE is the time-out specified by the /T parameter.
This idea was borrowed from Laurence Soucy, I added the /C
parameter to make it language independent (the simpler REM | CHOICE /T:N,10 >NUL
will work in many but not all languages).
The CHOICE
delay technique is demonstrated in the following example, Wait.bat:
-
@ECHO OFF
-
IF "%1"=="" GOTO Syntax
-
ECHO.
-
ECHO Waiting %1 seconds
-
ECHO.
-
REM | CHOICE /C:AB /T:A,%1 > NUL
-
IF ERRORLEVEL 255 ECHO Invalid parameter
-
IF ERRORLEVEL 255 GOTO Syntax
-
GOTO End
-
-
:Syntax
-
ECHO.
-
ECHO WAIT for a specified number of seconds
-
ECHO.
-
ECHO Usage: WAIT n
-
ECHO.
-
ECHO Where: n = the number of seconds to wait (1 to 99)
-
ECHO.
-
-
:End
-
Note: | The line ECHO Invalid parameter ends with an «invisible» BELL character, which is ASCII character 7 (beep) or ^G (Ctrl+G). |
In Windows 10 the REM
trick no longer works, and the default option is no longer specified with the /T
switch, but with a separate /D
switch:
CHOICE /C:AB /D:A /T:10 >NUL
This means that, unlike in DOS, in Windows 10 you can skip the delay by pressing one of the choices specified with the /C
switch.
The CHOICE
delay technique is demonstrated in the following example, Wait.cmd:
-
@ECHO OFF
-
IF NOT "%OS%"=="Windows_NT" GOTO Syntax
-
IF "%~1"=="" GOTO Syntax
-
ECHO.
-
ECHO Waiting %~1 seconds
-
ECHO.
-
CHOICE /C:AB /D:A /T:%1 > NUL
-
IF ERRORLEVEL 255 (
-
ECHO Invalid parameter
-
GOTO Syntax
-
)
-
GOTO:EOF
-
-
:Syntax
-
ECHO.
-
ECHO WAIT for a specified number of seconds
-
ECHO.
-
ECHO Usage: WAIT n
-
ECHO.
-
ECHO Where: n = the number of seconds to wait (1 to 99)
-
ECHO.
-
EXIT /B 1
-
💾 Download the Wait.bat and Wait.cmd source code
CountDown
For longer delay times especially, it would be nice to let the user know what time is left.
That is why I wrote CountDown.exe (in C#): it will count down showing the number of seconds left.
Pressing any key will skip the remainder of the count down, allowing the batch file to continue with the next command.
You may append the counter output to a custom text, like this (@ECHO OFF
required):
@ECHO OFF SET /P \"=Remaining seconds to wait: \" < NUL CountDown.exe 20
💾 Download CountDown.exe and its C# source code
SystemTrayMessage
SystemTrayMessage.exe is a program I wrote to display a tooltip message in the system tray’s notification area.
By default it starts displaying a tooltip which will be visible for 10 seconds (or any timeout specified), but the program will terminate immediately after starting the tooltip.
The icon will remain in the notification area after the timeout elapsed, until the mouse pointer hovers over it.
By using its optional /W
switch, the program will wait for the timeout to elapse and then hide the icon before terminating.
Display a tooltip message for 60 seconds while continuing immediately:
SystemTrayMessage.exe "Your daily backup has been started" /T:"Backup Time" /V:60 /S:186 REM Insert your backup command here
Display a tooltip message and wait for 60 seconds:
SystemTrayMessage.exe "It is time for your daily backup, please save and close all documents" /T:"Backup Time" /V:60 /S:186 /W REM Insert your backup command here
Or more sophisticated (requires CountDown.exe too):
-
@ECHO OFF
-
SET Message=It is time for your daily backup.\nPlease save and close all documents,\nor press any key to skip the backup.
-
START /B SystemTrayMessage.exe "%Message%" /T:"Backup Time" /V:20 /S:186 /W
-
ECHO Press any key to skip the backup . . .
-
SET /P "=Seconds to start of backup: " < NUL
-
CountDown.exe 20
-
IF ERRORLEVEL 2 (
-
ECHO.
-
ECHO Backup has been skipped . . .
-
EXIT /B 1
-
)
-
SystemTrayMessage.exe "Your daily backup has been started" /T:"Backup Running" /V:20 /S:186
-
REM Insert your backup command here
💾 Download SystemTrayMessage.exe and its C# source code
Non-DOS Scripting
In PowerShell you can use Start-Sleep
when you need a time delay.
The delay can be specified either in seconds (default) or in milliseconds.
-
Start-Sleep -Seconds 10 # wait 10 seconds
-
Start-Sleep 10 # wait 10 seconds
-
Start-Sleep -Seconds 2.7 # wait 3 seconds, rounded to integer
-
Start-Sleep -MilliSeconds 500 # wait half a second
The following batch code uses PowerShell to generate a delay:
-
@ECHO OFF
-
REM %1 is the number of seconds for the delay, as specified on the command line
-
powershell.exe -Command "Start-Sleep -Seconds %1"
Or if you want to allow fractions of seconds:
-
@ECHO OFF
-
REM %1 is the number of seconds (fractions allowed) for the delay, as specified on the command line
-
powershell.exe -Command "Start-Sleep -MilliSeconds ( 1000 * %1 )"
Note that starting PowerShell.exe in a batch file may add an extra second to the specified delay.
Use the SysSleep function whenever you need a time delay in Rexx scripts.
SysSleep is available in OS/2’s (native) RexxUtil module and in Patrick McPhee’s RegUtil module for 32-bits Windows.
Use the Sleep command for time delays in KiXtart scripts.
Use WScript.Sleep, followed by the delay in milliseconds in VBScript and JScript (unfortunately, this method is not available in HTAs).
The following batch code uses a temporary VBScript file to generate an accurate delay:
-
@ECHO OFF
-
REM %1 is the number of seconds for the delay, as specified on the command line
-
> "%Temp%.\sleep.vbs" ECHO WScript.Sleep %~1 * 1000
-
CSCRIPT //NoLogo "%Temp%.\sleep.vbs"
-
DEL "%Temp%.\sleep.vbs"
Or if you want to allow the user to skip the delay:
-
@ECHO OFF
-
REM %1 is the number of seconds for the delay, as specified on the command line
-
> "%Temp%.\sleep.vbs" ECHO Set wshShell = CreateObject( "WScript.Shell" )
-
>> "%Temp%.\sleep.vbs" ECHO ret = wshShell.Popup( "Waiting %~1 seconds", %~1, "Please Wait", vbInformation )
-
>> "%Temp%.\sleep.vbs" ECHO Set wshShell = Nothing
-
CSCRIPT //NoLogo "%Temp%.\sleep.vbs"
-
DEL "%Temp%.\sleep.vbs"
UNIX Ports
Compiled versions of SLEEP are also available in these Unix ports:
- CoreUtils for Windows
A collection of basic file, shell and text manipulation utilities - GNU utilities for Win32
Some ports of common GNU utilities to native Win32.
In this context, native means the executables only depend on the Microsoft C-runtime (msvcrt.dll) and not an emulation layer like that provided by Cygwin tools.
page last modified: 2023-09-12; loaded in 0.0075 seconds
In the world of Windows scripting, batch files are a powerful tool for automating repetitive tasks. Sometimes, it’s necessary to pause or delay the execution of a script for a specific period. This can be useful in various scenarios, such as waiting for a network service to start, allowing time for a file to unlock, or simply pacing the execution of commands to prevent overwhelming system resources. In this guide, we will explore how to implement sleep and wait functions in Windows batch scripts effectively.
Using timeout Function
The primary method to introduce a delay in a batch script is by using the timeout command. This command pauses the script for a specified number of seconds. Here’s how to use it:
Syntax:
timeout /t <Seconds> [/nobreak]
- `/t `: Specifies the number of seconds to wait. Replace with the actual number of seconds you want the script to pause.
- `/nobreak`: An optional parameter that prevents the pause from being interrupted by key presses, except CTRL+C.
Command-line Example
For example to wait for 5 seconds use. Use /T options:
c:/> timeout /T 5
Batch Script Example
@echo off
echo Waiting for 10 seconds...
timeout /t 10
echo Resuming execution.
In this example, the script will pause for 10 seconds before printing “Resuming execution.”
For more complex scripts that might be running on Windows systems with additional utilities or in environments like Cygwin, the sleep command can also be used to introduce a delay.
Syntax
sleep <Seconds>
However, the sleep command might not be available in all Windows installations, as it’s part of the Resource Kit Tools or needs to be installed separately in some Unix-like environments on Windows.
Best Practices
- Use the timeout command where possible for its simplicity and built-in support in modern Windows environments.
- When using the ping method for compatibility with older systems, be aware of its limitations and inaccuracies.
Conclusion
Adding sleep or wait functions in Windows batch scripts can be achieved through several methods, depending on your requirements and the specifics of the operating system. Whether through the straightforward timeout command, the legacy ping method, or the sleep command in certain environments, you can effectively control the flow of your batch scripts with these techniques. Remember to consider the context in which your script will run and choose the method that best suits your needs.