The `timeout` command in Windows CMD is used to pause the command execution for a specified number of seconds, allowing you to create delays in your scripts or commands.
Here’s the syntax for a 10-second pause:
timeout /t 10
Understanding the Sleep Command in CMD
What is the Sleep Command?
The Sleep Command in Windows CMD is a functional tool that temporarily pauses the execution of commands for a specified duration. It is particularly useful in scripting and automation, allowing users to control when a subsequent command or series of commands should run after a deliberate delay.
The purpose of the Sleep Command varies widely and can include:
- Coordinating tasks: When scripts require multiple commands to run in a specific order with necessary delays.
- Resource management: Preventing resource overutilization by pacing operations, ensuring that the system does not get overloaded.
Syntax of the Sleep Command
The basic syntax for the Sleep Command is simple:
sleep [duration]
- duration is typically specified in milliseconds. For example, a sleep duration of 5000 would pause execution for five seconds.
Example of Basic Syntax
If you wanted to pause your CMD session for 3 seconds, you would write:
sleep 3000
This command instructs the command line interface to halt all further commands for 3000 milliseconds.
Lock Windows Cmd: A Quick Guide to Securing Your Commands
How to Use the Sleep Command in Windows CMD
Setting Up Your Command Prompt
To get started with the Sleep Command, you must access the Command Prompt. Follow these steps to open CMD:
- Press `Win + R` to open the Run dialog.
- Type `cmd` and hit `Enter`.
Ensure that you are running a compatible version of Windows that supports CMD and the Sleep functionality.
Using the Sleep Command Effectively
Basic Examples
One common way to achieve a pause in CMD is using the timeout command, which allows for similar functionality.
timeout /t [seconds]
For instance, to pause for 10 seconds:
timeout /t 10
This command is another way to create a delay, but take note that using timeout will allow the user to interrupt the pause by pressing a key, whereas Sleep will not.
Advanced Usage
One of the most powerful scenarios for using Sleep is in a Batch File. Batch files automate sequences of commands, and incorporating the Sleep command helps manage timing.
Here’s a simple example:
@echo off
echo Starting the process...
sleep 5000
echo Process is running...
sleep 2000
echo Process completed.
In this script, there is a 5-second pause before and a 2-second pause after outputting messages, illustrating how well Sleep can enhance automation flow.
Understanding Duration Parameters
Getting comfortable with duration measurements is crucial. Sleep accepts time in milliseconds, which necessitates some conversions for those accustomed to seconds.
For example:
- To pause for 1 minute, you would specify 60000 milliseconds.
- For 30 seconds, you would use 30000.
By understanding how to express time in the Sleep command, your ability to control execution timing becomes more precise.
Mastering SSH in Windows Cmd: A Quick How-To Guide
Practical Applications of Sleep Command
Automation Scripts
In automated tasks, timing can significantly affect the process’s success. Incorporating Sleep means you can ensure that each segment of a script waits patiently for resources to become available.
For instance, consider a system maintenance script that needs to stop a service, wait, and then restart it:
net stop "ServiceName"
sleep 10000
net start "ServiceName"
In this example, there is a deliberate pause of 10 seconds after stopping a service to ensure the system has time to release resources before restarting.
Delaying Commands
Delays can often be crucial in scripting, especially when dealing with dependencies. If one command relies on the successful completion of another, a sleep command ensures that the second command does not run prematurely.
For instance:
echo Starting backup...
robocopy C:\Data D:\Backup /E
sleep 5000
echo Backup completed successfully!
Here, using Sleep gives a clear window of time after the robocopy command before notifying the user that the backup process has finished.
Controlling System Resources
By spacing commands out, you can manage system resources more effectively. For example, if you’re deploying updates across multiple systems, adding pauses allows each machine to stabilize before executing the next command.
Consider this scenario:
call update-script.bat
sleep 60000
call another-script.bat
This ensures that the update script has ample time to process before moving on to the next batch of commands, avoiding potential conflicts.
Repair Windows Cmd: Quick Fixes and Tips
Troubleshooting Common Issues
CMD Not Recognizing Sleep Command
At times, you might encounter issues where your CMD doesn’t recognize the Sleep command. This often stems from:
- Missing utility: Ensure that the Sleep command is available by using Windows versions that support it rather than compatibility modes.
- Path issues: You may have to add the path to your Windows system files in your environment variables.
Performance Issues Related to Sleep
In some scenarios, excessive use of Sleep can result in performance degradation, especially in lengthy scripts. Long sleep durations can lead to scripts running for an extended period unnecessarily.
Tips to optimize:
- Use shorter sleep durations when possible.
- Analyze whether pauses are essential for command execution logic.
List in Windows Cmd: Quick and Easy Commands Explained
Conclusion
The Sleep command in Windows CMD is a versatile and powerful tool that caters to a variety of automation needs. By mastering its functionality, users can wait for events to complete, pace command execution, and effectively manage system resources. Experimenting with this command can significantly enhance your command line proficiency and improve script efficiency.
Copy Folder Windows Cmd: A Quick How-To Guide
Additional Resources
Links to Further Readings
For further exploration, consider the following resources:
- Books on CMD scripting and automation practices.
- Official Microsoft Documentation on CMD commands.
FAQs
You may wonder:
- What other alternatives exist for implementing pauses?
- How does Sleep interact with system performance?
These common questions will enhance your understanding and encourage exploration beyond the Sleep command itself. Whether you’re a newbie or an experienced user, the world of CMD offers myriad commands to discover and utilize!
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.0080 seconds
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?
The Sleep/Wait Command is a very useful command that is used to pause for a set amount of time while a batch script is being executed. To put it another way, this command makes it easier to run a command for a set amount of time.
Table of Contents
- 1 Using timeout to achieve sleep function
- 2 Using Ping to Delay to achieve sleep function
- 3 Using Ping to Delay with nonexisting IP
- 4 Using Ping to Delay in less than 1 second.
- 5 Using Powershell in Command to delay
- 6 Using Powershell in Sleep Start Command to delay
- 7 Using the Mshta command
You may find yourself in a situation where you want to run a series of command lines one after the other, but with a time delay between them. In this case, the sleep command will come in handy. This article will show you how to use the sleep command in Windows batch scripts.
📚 Note: Windows does not have a direct Sleep command as provided in Linux, we must use a different method to achieve the same result. Furthermore, no root privileges are required to implement in a batch script.
1 Using timeout to achieve sleep function
timeout is an old Windows command introduced in Windows 2000 that is used to add a delay between two tasks.
Usage :
timeout /t [/nobreak]
Here,
/t
|
Specify the number of seconds to wait (between -1 and 99999) before the command processor continues processing. When you enter the value -1, the computer will wait indefinitely for a keystroke. Also, a number of seconds in a nonwhole number like 1.5 is not accepted. |
/nobreak | Specifies to ignore user keystrokes. But accepts CTRL + C strokes which directly terminate the batch. |
/? | Displays help at the command prompt. |
Example1: Basic timeout in Batch Script
@echo off
echo First Task Here …
echo Approximately 10-second delay
timeout /t 10
echo Second Task Here …
pause
We have two tasks here, and we have inserted a timeout script that waits for 10 seconds for the First Task to complete before starting the Second Task.
In details:
«@echo off» disables the console window command display in this Windows batch file script. After this line, console commands will not be displayed.
The terminal window will display «echo First Task Here» after the next line. Displays the provided text in the console window.
«echo About 10-second delay» informs the user of a delay in the console window.
«Timeout /t 10» will postpone script execution for 10 seconds. The console window will countdown the remaining time.
«echo Second Task Here…» will appear in the terminal window after the wait, restarting script execution.
Lastly, the «pause» command pauses script execution and displays «Press any key to resume…«, allowing the user to inspect the console window output before closing it. After «pause,» the script must be resumed by pressing any key.
Drawback: This will show unnecessary «Waiting for 0 seconds, press a key to continue…» and when you press any key it will continue to the next task. It is a good way of letting the user know the safe escape route to skip sleep.
Example2: Timeout with only CTRL + C key to Skip
@echo off
…..
timeout /t 10 /nobreak
…..
pause
Here, /nobreak does not allow to break or skip sleep with any key. But pressing the CTRL + C key combination will force to close the batch processing and close the program immediately.
Example 3: Sleep without timeout message
@echo off
….
timeout /t 15 /nobreak > nul
….
pause
Appending >nul part so that the command does not display output anything to the screen. It suppresses the countdown time.
Another best use case of the timeout is as follows:
calc && timeout 5 && notepad
This will open the calculator, then wait 5 seconds before opening the notepad. Remember to include and && between each block. You can continue to cascade it like shown below
calc && timeout 3 && notepad && timeout 4 && regedit
This will open the calculator, then wait 3 seconds for the notepad to open, then wait 4 seconds for the registry editor to open.
Note that: Ctrl + C will break the whole program.
Drawbacks of TIMEOUT
Here are some drawbacks of timeout :
- Cannot perform delay in a fraction of a second. ie. like timeout /t 0.5 does not work. And will give
an error message stating «Error: Invalid value for timeout (/T) specified. The valid range is -1 to 99999) - Cannot use a second value greater than 99999
2 Using Ping to Delay to achieve sleep function
@echo off
…..
ping localhost -n 10 > nul
…..
pause
Ping is actually used to determine whether or not a resource responds to a request. Ping sends a request to the resource and waits one second for a response. As a result, it is useful to use it as a delay function. Even if it waits for one second, it may receive a response in a few milliseconds. However, as soon as you ping the last packet here in the tenth request, it will automatically stop.
The resource we are pinging here is localhost, which is a local loopback, and it responds instantly within a millisecond but must wait 1 second each. And here in the example, we are waiting for nearly 10 seconds before executing the next line.
Note that: Ctrl + C will break the delay.
3 Using Ping to Delay with nonexisting IP
@echo off
….
ping 192.4.4.4 -n 1 -w 10000 > nul
….
pause
Here waiting for 10 seconds. Here we must ping a non-existing IP address and if it exists it will not work. -w indicates waiting and here it waits for 10000 ms, you can change this value. And by default ping will request 4 times to the resource. Here, -n 1 indicates request only 1 time.
4 Using Ping to Delay in less than 1 second.
Just replace 10000ms with anything smaller than 1000ms. like 500ms as shown below
ping 192.4.4.4 -n 1 -w 500 > nul
5 Using Powershell in Command to delay
Simply follow the simple example below if you want to use Powershell commands from the command line:
Example 1
powershell -command «Please Wait for 5 second» -s 5
type this command in the command line or batch file. This command will hold the screen for 5 seconds. You can change it from 5 to any number. This can be useful if a Windows command fails or has an issue.
Example 2:
powershell -nop -c «& {sleep -m 5}»
6 Using Powershell in Sleep Start Command to delay
Alternatively, you can sleep-start command of Powershell in CMD as below:
powershell -ExecutionPolicy Bypass -Command "Start-Sleep -Seconds 5"
The above command will wait for 5 seconds. Note that: Method 5 is a short form of method 6
powershell -ExecutionPolicy Bypass -Command "Start-Sleep -MilliSeconds 500"
The above command will wait for 500 milliseconds.
7 Using the Mshta command
Mshta.exe is a native Windows binary that was developed specifically for the purpose of executing Microsoft HTML Application (HTA) files.Mshta is able to run code written in Windows Script Host (VBScript and JScript) that is embedded into HTML in a manner that is aware of network proxies.
start "" /w /b /min mshta "javascript:setTimeout(function(){close();},5000);"
Conclusion:
To summarize, in Windows batch files, you can pause the execution of the batch file for a specified number of seconds by using the «sleep» command, and you can create a custom «wait» command by using the «timeout» command. Both of these commands can be found in the «commands» section of the batch file. While the «wait» command can be used to wait for a defined number of seconds before continuing with the next command, the «sleep» command is used to pause the execution of the batch file for a specified number of seconds at a time. You will be able to regulate the timing and flow of your batch file by using these commands, which will enable you to ensure that it runs smoothly and effectively.
FAQ:
What is the WaitFor command?
Waitfor.exe is a small utility that is included with Windows 7 and later versions. This program is designed to listen for and respond to a named signal. Visit here for more info.
Is there a command in Windows that allows you to sleep and wait?
There is no sleep and wait-for command in the windows version. The best alternative is the Timeout command as explained above. In Linux, you can simply use: sleep n in the terminal where n is time in seconds.
How to sleep for five seconds in a batch file?
A simple way to do this in a batch file before and after the task you want to sleep or hold is as follows:
timeout /t 5 /nobreak >nul
Overview
The SLEEP
command in Windows CMD is used to pause the execution of a batch file for a specified number of seconds. This can be particularly useful in scripts where a delay is required between commands, such as waiting for a network service to start or pausing between deployments of different components. SLEEP
provides a simple way to introduce a time delay in automated scripts and workflows.
Syntax
The syntax for the SLEEP
command is straightforward:
SLEEP time_in_seconds
time_in_seconds
: This is the number of seconds that the command processor will pause before continuing with the next command in the script.
Options/Flags
The SLEEP
command does not have any options or flags. It simply takes the number of seconds to pause as its sole argument. The absence of options makes it an easy-to-use command without complications.
Examples
-
Basic Usage: Pause a script for 10 seconds.
SLEEP 10
This command will halt the script for 10 seconds before proceeding with the subsequent commands.
-
Using
SLEEP
in a loop: Example of a countdown from 5 seconds.FOR /L %i IN (5,-1,1) DO (ECHO %i & SLEEP 1)
This loop counts down from 5 to 1, pausing for 1 second between each number.
Common Issues
No Fractional Seconds: The SLEEP
command does not support fractional seconds. If a fraction is provided, the command rounds down to the nearest whole number. To wait for less than a second, consider using alternative methods like PowerShell’s Start-Sleep -Milliseconds 500
.
Script Execution Stops Unexpectedly:
If a script containing the SLEEP
command is executed without admin rights where required, or if there are system restrictions, the script may halt unexpectedly. Always ensure appropriate permissions are granted for the scripts to execute correctly.
Integration
SLEEP
is often used in conjunction with other CMD commands to manage the timing of operations. Here’s an example of using SLEEP
with other commands in a batch script:
@ECHO OFF
ECHO Waiting for system processes to settle...
SLEEP 5
ECHO Launching backup...
START backup_script.bat
In this script, SLEEP
is integrated to provide a pause before starting a backup operation.
TIMEOUT
: Similar toSLEEP
, but includes the ability to interrupt the wait by pressing a key.PING
: Sometimes used as a workaround to create delays, especially whenSLEEP
is not available in older versions of Windows. Example:PING 127.0.0.1 -n 6 > NUL
to wait approximately 5 seconds.
For further details and additional parameters, you can refer to the official Microsoft documentation.
This command works well in various scripting cases, particularly in automation processes, where a delay needs to be enforced between command executions or to simulate staggered starts.