757

Windows's Snipping tool can capture the screen, but sometimes I want to capture the screen after five seconds, such as taking an image being displayed by the webcam. (Run the script and smile at the camera, for example.)

How do I sleep for 5 seconds in a batch file?

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
nonopolarity
  • 130,775
  • 117
  • 415
  • 675
  • 18
    Quick answer for people landing here; there is a native solution since Windows Vista: `TIMEOUT`. Refs: [SS64](https://ss64.com/nt/timeout.html), [Rob van der Woude](http://www.robvanderwoude.com/wait.php). – Gras Double Aug 07 '17 at 00:50
  • 1
    There is [timeout](https://ss64.com/nt/timeout.html) command that waits for seconds. In case if millisecond sleep is needed, powershell's [Start-Sleep](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/start-sleep?view=powershell-6) can be used. To sleep 50ms in cmd: `powershell Start-Sleep -m 50` – Pavel P Feb 22 '18 at 05:37
  • @Pavel: You can also misuse a ping to a non-existent host to sleep for milliseconds. – Joey Mar 01 '18 at 10:58
  • A good summary of the various techniques to halt a batch file process: https://www.robvanderwoude.com/wait.php – 1934286 Jan 03 '19 at 01:32
  • 7
    Try This : `timeout /t 5 /nobreak >nul` –  Aug 06 '19 at 10:37
  • just for fun, if you have Node.js installed, you can use `node -e 'setTimeout(a => a, 5000)'` it works on a Mac with Node v12.14.0 and probably on Windows too – nonopolarity Dec 28 '19 at 14:55
  • Yet another option: `powershell "Sleep 3"` – Fiach Reid Jan 13 '21 at 10:32

30 Answers30

1588

I'm very surprised no one has mentioned:

C:\> timeout 5

N.B. Please note however (thanks Dan!) that timeout 5 means:

Sleep anywhere between 4 and 5 seconds

This can be verified empirically by putting the following into a batch file, running it repeatedly and calculating the time differences between the first and second echos:

@echo off
echo %time%
timeout 5 > NUL
echo %time%
Evgeniy Berezovsky
  • 16,237
  • 8
  • 74
  • 131
asveikau
  • 35,672
  • 2
  • 48
  • 66
  • 34
    'timeout' is not recognized as an internal or external command, operable program or batch file. (On my Windowx XP SP3) – noctonura Nov 04 '09 at 08:30
  • 95
    it works on Win 7, but not on Win XP – nonopolarity Nov 04 '09 at 08:34
  • 7
    I'm fairly certain I've used it on Server 2003 (same code base as XP), so it's a wonder it's not on XP then... – asveikau Nov 04 '09 at 09:56
  • 2
    Because XP is not Server 2k3. Heck, it's two years older and historically (excluding NT 4) the server OSes came with some stuff that wasn't there in the workstation variant. – Joey Nov 04 '09 at 10:03
  • 2
    timeout was introduce with Vista according to this site http://commandwindows.com/vista-tips.htm#timeout – Adam Porad May 05 '10 at 18:10
  • found one in cygwin > which timeout > /usr/bin/timeout – Kalpesh Soni Jun 01 '12 at 20:07
  • 48
    Timeout is poorly implemented. If you do a "timeout 1", it will wait until the "next second," which could occur in .1 seconds. Try doing "timeout 1" a few times and observe the difference in delay. For 5 seconds or more, it may not be a big deal, but for a 1 second delay it works poorly. – Dan Sep 18 '12 at 19:31
  • 3
    Also, you will likely want the '/nobreak' option. Otherwise, it finishes the timeout immediately on receiving a key press event. – Stephen Feb 20 '13 at 00:01
  • It's not precise, but it works out of the box on Windows 8. – Dana May 29 '13 at 18:06
  • 1
    As of today (May 2nd 2014), we can assume that this is the proper answer. WinXP is not supported anymore and it seems to be the only Windows OS with that function missing. – Maxime Rouiller May 02 '14 at 14:10
  • 78
    `timeout` does not work in non-interactive scripts: "ERROR: Input redirection is not supported, exiting the process immediately." – Daniel Jun 28 '14 at 21:21
  • yes, is the better solution! – elle0087 Nov 27 '14 at 09:50
  • I like when things are done right ;) – AquaAlex Apr 24 '15 at 12:44
  • @Dan so do not use 1 second use 2 seconds :D – AquaAlex Apr 24 '15 at 12:45
  • @Dan I'd also argue that, if that's how `timeout` is designed, it is _not_ poorly implemented, it's just a poor solution to this problem! It might be useful in other circumstances to wait for the next second boundary... – Ian Apr 27 '15 at 11:15
  • 3
    @Ian I'd argue that it's either poorly implemented or poorly documented if that's how it's designed. It specifically says in `timeout /?` that it will "wait for the specified time period (in seconds)". 0.1 second is a big difference from 1.0 and this has been a major thorn in my side and isn't something I can rely on for short(ish) timeouts – Adam Plocher May 18 '15 at 22:04
  • @AdamPlocher In that case, I'll retract my argument! :) – Ian May 19 '15 at 13:44
  • I am observing strange issue with timeout command, I have added 'timeout /t 275 /nobreak'. What I see is instead of 275 seconds, timeout is getting done in around 177 seconds. any ideas? – Anurag Daware Dec 02 '15 at 10:18
  • Works great in Windows 10. – HerrimanCoder May 11 '16 at 11:18
  • 2
    not working in JENKINS: `ERROR: Input redirection is not supported, exiting the process immediately.` – Yar Jun 13 '16 at 19:04
  • 3
    @Yar Consider using `START /WAIT TIMEOUT /T x /NOBREAK >NUL` for non-interactive scripts. – Jimadine Jan 31 '18 at 11:08
  • timeout not worked for me, even when used /NOBREAK command when caller is a C++ program. The ping workaround worked for that ... – hfrmobile Feb 26 '18 at 10:22
  • This answers the question of OP. Works in BAT file. Standard Windows, timeout.exe is in c:\windows\system32\ . (Win7) The manual is, as usual, in: timeout /? – Roland Mar 27 '18 at 08:44
  • pretty old, but just for completeness, while timeout DID work for me in a batch file executed from Windows 7 SP1 shell directly, when using Java and ProcessBuilder to run it it did not wait. ping solution, by the way, worked like a charm (which is the solution I was using before) – DGoiko Jan 18 '20 at 15:34
898

One hack is to (mis)use the ping command:

ping 127.0.0.1 -n 6 > nul

Explanation:

  • ping is a system utility that sends ping requests. ping is available on all versions of Windows.
  • 127.0.0.1 is the IP address of localhost. This IP address is guaranteed to always resolve, be reachable, and immediately respond to pings.
  • -n 6 specifies that there are to be 6 pings. There is a 1s delay between each ping, so for a 5s delay you need to send 6 pings.
  • > nul suppress the output of ping, by redirecting it to nul.
MultiplyByZer0
  • 4,341
  • 3
  • 27
  • 46
Martin
  • 36,545
  • 20
  • 97
  • 129
  • 8
    This doesn't work well for me (could be a networking issue)? When I try the above command (without the pipe to nul) I immediately get a "Destination host unreachable" from the gateway server and the ping command exits straight away. – Ian Renton Mar 27 '12 at 15:12
  • 131
    It's cleaner and more reliable, IME, to do "ping 127.0.0.1 -n 10 > nul" - each ping waits 1s, so change the number of times to the number of seconds you wish to delay. – Cybergibbons Jun 08 '12 at 11:17
  • 41
    One correction - 1.1.1.1 is a perfectly valid _public_ IP address. Theoretically, it may be reached. It's offline now because I suspect their owners gave up hope to use it for anything but pings from all over the world :) For more details on this IP see http://serverfault.com/a/339782. It's saver to either use 127.0.0.1 as suggested by Cybergibbons, or one of the _private_ addresses that don't exist in your network (e.g. 10.1.1.1, etc). – Alex Jun 15 '13 at 19:47
  • 39
    @Cybergibbons Beware fence-post error here. There is a 1s delay *between* each ping, so for a 10s delay you need to do 11 pings, i.e. "ping 127.0.0.1 -n 11 > nul" – gb96 Jul 11 '13 at 00:39
  • 8
    II recommend to use 127.0.0.1 (localhost), if I have a problems with Internet, it isn't work :/ – barwnikk Oct 13 '13 at 09:46
  • this tactic of using some ip like 1.1.1.1 may impact other network application when compounded with other app or task that does the same thing. timeout, or choice /T etc may be a better choice with far less likelyhood of interference on other task or apps. – gg89 Feb 04 '15 at 06:53
  • 1
    Yes, use an IP address like 127.0.0.1 (or just the text "localhost"), which is valid. To use an invalid IP address causes ping to trip up the ERRORLEVEL. – macetw Feb 25 '15 at 13:53
  • 2
    1.1.1.1 Is now owned by CloudFlare, so it'll certainly be reachable. – Brandon Sturgeon Jun 12 '18 at 07:36
  • 2
    This was basically edited until it [plagiarises this answer](https://stackoverflow.com/a/1672350/1837991) – Gert van den Berg Dec 31 '18 at 06:39
  • @GertvandenBerg There was only one edit that changed one line of code such that it is now similar (but still different) from the post you linked. – TylerH Jan 24 '19 at 20:00
  • @TylerH: The point of this answer (and all the comments on it) was to ping an "invalid" IP (which was actually perfectly valid but not assigned at that time) and use `-w` to delay it, not to ping localhost. In 2015 compie edited it with the same code as that answer. – Gert van den Berg Jan 25 '19 at 08:39
  • @GertvandenBerg It's not the same, just very similar. This is not to say I don't agree with the concern of changing the answer. I would recommend raising a question on Meta about what to do with this answer (e.g. roll it back completely? edit it to show the old code and update the explanation? leave it as it is?); there is no obvious choice either way. – TylerH Jan 25 '19 at 15:17
  • Since it was in a batch file I had to use `@"C:\Windows\system32\ping" 127.0.0.1 -n %1% -w 1000 > nul` (I don't recall why I added `-w 1000`!). – SharpC Mar 26 '19 at 20:46
73

Try the Choice command. It's been around since MSDOS 6.0, and should do the trick.

Use the /T parameter to specify the timeout in seconds and the /D parameter to specify the default selection and ignore then selected choice.

The one thing that might be an issue is if the user types one of the choice characters before the timeout period elapses. A partial work-around is to obfuscate the situation -- use the /N argument to hide the list of valid choices and only have 1 character in the set of choices so it will be less likely that the user will type a valid choice before the timeout expires.

Below is the help text on Windows Vista. I think it is the same on XP, but look at the help text on an XP computer to verify.

C:\>CHOICE /?

CHOICE [/C choices] [/N] [/CS] [/T timeout /D choice] [/M text]

Description:
    This tool allows users to select one item from a list
    of choices and returns the index of the selected choice.

Parameter List:
   /C    choices       Specifies the list of choices to be created.
                       Default list is "YN".

   /N                  Hides the list of choices in the prompt.
                       The message before the prompt is displayed
                       and the choices are still enabled.

   /CS                 Enables case-sensitive choices to be selected.
                       By default, the utility is case-insensitive.

   /T    timeout       The number of seconds to pause before a default
                       choice is made. Acceptable values are from 0 to
                       9999. If 0 is specified, there will be no pause
                       and the default choice is selected.

   /D    choice        Specifies the default choice after nnnn seconds.
                       Character must be in the set of choices specified
                       by /C option and must also specify nnnn with /T.

   /M    text          Specifies the message to be displayed before
                       the prompt. If not specified, the utility
                       displays only a prompt.

   /?                  Displays this help message.

   NOTE:
   The ERRORLEVEL environment variable is set to the index of the
   key that was selected from the set of choices. The first choice
   listed returns a value of 1, the second a value of 2, and so on.
   If the user presses a key that is not a valid choice, the tool
   sounds a warning beep. If tool detects an error condition,
   it returns an ERRORLEVEL value of 255. If the user presses
   CTRL+BREAK or CTRL+C, the tool returns an ERRORLEVEL value
   of 0. When you use ERRORLEVEL parameters in a batch program, list
   them in decreasing order.

Examples:
   CHOICE /?
   CHOICE /C YNC /M "Press Y for Yes, N for No or C for Cancel."
   CHOICE /T 10 /C ync /CS /D y
   CHOICE /C ab /M "Select a for option 1 and b for option 2."
   CHOICE /C ab /N /M "Select a for option 1 and b for option 2."
Adam Porad
  • 13,054
  • 2
  • 30
  • 54
71

The following hack let's you sleep for 5 seconds

ping -n 6 127.0.0.1 > nul

Since ping waits a second between the pings, you have to specify one more than you need.

OldMcDonald
  • 545
  • 10
  • 31
noctonura
  • 11,595
  • 10
  • 45
  • 79
  • 36
    This should be `-n 6`. Otherwise you just wait 4 seconds. Remember that `ping` waits 1 second *between* pings, so you always have to specify one more try than you need. – Joey Nov 04 '09 at 10:01
  • 5
    This is a much better solution than pinging a presumed non-existing IP, which by the way fails when network is down. Pinging localhost almost always works. – rustyx May 09 '14 at 08:01
  • Should be `> null` if you're using powershell. – Brent Nov 01 '16 at 23:15
50

If you've got PowerShell on your system, you can just execute this command:

powershell -command "Start-Sleep -s 5"

Edit: people raised an issue where the amount of time powershell takes to start is significant compared to how long you're trying to wait for. If the accuracy of the wait time is important (ie a second or two extra delay is not acceptable), you can use this approach:

powershell -command "$sleepUntil = [DateTime]::Parse('%date% %time%').AddSeconds(5); $sleepDuration = $sleepUntil.Subtract((get-date)).TotalMilliseconds; start-sleep -m $sleepDuration"

This takes the time when the windows command was issued, and the powershell script sleeps until 5 seconds after that time. So as long as powershell takes less time to start than your sleep duration, this approach will work (it's around 600ms on my machine).

Niall Connaughton
  • 14,009
  • 10
  • 50
  • 46
  • 28
    Simply loading up PowerShell takes a few seconds. – Synetech Dec 29 '13 at 02:02
  • Well 600ms isn’t too bad, but that’s on your OS on your hardware. PowerShell takes about six seconds to load on XP the first time it is run in a Windows session, then about three seconds for subsequent runs. In Windows 7 on the same system, it takes less and on a faster system even less. In short, this isn’t a very portable solution. – Synetech Jan 06 '14 at 00:26
  • Did you try the alternate solution I pasted? – Niall Connaughton Jan 06 '14 at 00:34
  • It doesn't have any protection from the case where the powershell startup lag is longer than the sleep duration, but that would be easy enough to add – Niall Connaughton Jan 06 '14 at 00:37
  • 3
    I ended up using this myself. Running the plain 5 second sleep takes about 5.5 seconds - 5.6 seconds to complete on my machine. Using the second script I posted gets the inaccuracy down to around 20 - 30 milliseconds. If you need more accuracy than this, I doubt you'll get it from the ping approach either. – Niall Connaughton Jun 02 '14 at 00:16
  • 2
    @NiallConnaughton Can you test with –NoProfile and see how much that affects the speed? This avoids loading the user's profile which should prevent a disk search and file access as well as any "plugins/modules/etc" that get added to the user's profile. – dragon788 Jun 24 '16 at 19:01
  • 1
    Apparently there are 6 potential profiles that PowerShell will try to load if you don't pass -NoProfile. https://blogs.technet.microsoft.com/heyscriptingguy/2012/05/21/understanding-the-six-powershell-profiles/ – dragon788 Jun 24 '16 at 19:07
  • 1
    On my current system, there's a 150ms cost to starting powershell, and -noprofile isn't improving that. However, this machine is not on a corporate domain with a roaming profile, etc. YMMV. Good suggestion. – Niall Connaughton Jul 17 '16 at 10:29
42

You can make it with timeout:

This will be visible: timeout 5

This will not be visible timeout 5 >nul

Alex
  • 459
  • 1
  • 5
  • 8
35

Can't we do waitfor /T 180?

waitfor /T 180 pause will result in "ERROR: Timed out waiting for 'pause'."

waitfor /T 180 pause >nul will sweep that "error" under the rug

The waitfor command should be there in Windows OS after Win95

In the past I've downloaded a executable named sleep that will work on the command line after you put it in your path.

For example: sleep shutdown -r -f /m \\yourmachine although shutdown now has -t option built in

Chris Marisic
  • 30,638
  • 21
  • 158
  • 255
joe li
  • 351
  • 3
  • 2
31

Timeout /t 1 >nul

Is like pause in 1 secound, you can take the limed to almost 100.000 (99.999) secounds. If you are connected to the internet the best solution would be:

ping 1.1.1.1. -n 1 -w 1000 >nul

When you ping you count in milliseconds, so one second would be 1000 milliseconds. But the ping command is a little iffy, it does not work the same way on offline machines. The problem is that the machine gets confused because it is offline, and it would like to ping a website/server/host/ip, but it can't. So i would recommend timeout. Good luck!

Alex Nolasco
  • 17,012
  • 9
  • 71
  • 76
Jonathan
  • 459
  • 5
  • 8
  • 9
    Pinging to 1.1.1.1 is not a good and really not the best solution. It causes network traffic. Ping to localhost instead. – harper Dec 22 '14 at 11:23
  • 1
    The point of pinging an unreachable IP address is to cause the command to wait for a response and timeout after the specified time. "localhost" is likely to reply rather than timeout on most systems. – Ivan Jun 01 '17 at 13:12
  • 1
    @user3070485 But [1.1.1.1](https://1.1.1.1) is not unreachable. Why not use something like 192.0.2.1, which is guaranteed to be unreachable? – Lena Apr 02 '18 at 07:06
  • 1.1.1.1 *used to be* unreachable @Tijmen. I've seen it used many times as a very bad example of an "unreachable" address. – bzlm Apr 04 '18 at 18:14
  • 1
    I shudder to think of all the scripts that suddenly broke when Cloudflare started responding to pings on 1.1.1.1. – mwfearnley Dec 09 '19 at 16:16
25

SLEEP 5 was included in some of the Windows Resource Kits.

TIMEOUT 5 was included in some of the Windows Resource Kits, but is now a standard command in Windows 7 and 8 (not sure about Vista).

PING 1.1.1.1 -n 1 -w 5000 >NUL For any MS-DOS or Windows version with a TCP/IP client, PING can be used to delay execution for a number of seconds.

NETSH badcommand (Windows XP/Server 2003 only) or CHOICE

this link will help you more.

Amir
  • 1,266
  • 14
  • 23
18

Two answers:

Firstly, to delay in a batch file, simply without all the obtuse methods people have been proposing:

timeout /t <TimeoutInSeconds> [/nobreak] 

http://technet.microsoft.com/en-us/library/cc754891.aspx

Secondly, worth mentioning that while it may not do exactly what you want, using the inbuilt Windows snipping tool, you can trigger a snip on it without using the mouse. Run the snipping tool, escape out of the current snip but leave the tool running, and hit Control + Print Screen when you want the snip to occur. This shouldn't interfere with whatever it is you're trying to snip.

Ned Martin
  • 457
  • 5
  • 10
12

I was trying to do this from within an msbuild task, and choice and timeout both did not work due to I/O redirection.

I ended up using sleep.exe from http://sourceforge.net/projects/unxutils, which is nice because it doesn't require any install and it's tiny.


Trying with choice:

<Target Name="TestCmd">
  <Exec Command="choice /C YN /D Y /t 5 " />
</Target>

Results in:

TestCmd:
  choice /C YN /D Y /t 5

EXEC : error : The file is either empty or does not contain the valid choices. [test.proj]
  [Y,N]?
C:\test.proj(5,9): error MSB3073: The command "choice /C YN /D Y /t 5 " exited with code 255.

Trying with timeout:

<Target Name="TestCmd">
  <Exec Command="timeout /t 5 " />
</Target>

Results in:

TestCmd:
  timeout /t 5
EXEC : error : Input redirection is not supported, exiting the process immediately. [test.proj]
C:\test.proj(5,7): error MSB3073: The command "timeout /t 5 " exited with code 1.

Aside:

I am actually using <Exec Command="sleep 2 & dbghost.exe" /> because I am executing dbghost.exe multiple times in parallel and it creates temp files/databases based on the current epoch time in seconds - which of course means if you start multiple instances, each uses the same temp name. I was originally trying to use MSBuild Extension Pack Thread.Sleep command, but it seems that (usually) it was running the sleep task fine, but then starting the <exec> task in all threads at the same time, and of course dbghost.exe would fail with conflicts. So far, using sleep.exe seems to be more reliable.

gregmac
  • 22,527
  • 9
  • 79
  • 114
  • 2
    Extremely helpful note about choice/timeout not working within an msbuild task. In that case I did find the accepted answer (ping) worked for me within msbuild: ping 1.1.1.1 -n 1 -w 3000 > nul – Steve Cadwallader Feb 12 '14 at 16:00
  • Also choice/timeout does not work in an Ant task either. – DonBecker Aug 17 '15 at 17:42
  • FOR BUILD SERVERS! `CHOICE` and `TIMEOUT` don't work under a non-interactive process/account. Forget about them on build-machines. `PING 1.1.1.1` doesn't work if your network connection fails. Look around here for `W32TM`, `TypePerf`, some PowerShell. Or create your custom .NET executable. – it3xl Jul 08 '19 at 17:28
11

There is!

SLEEP <seconds>

If you want it in millisecond mode:

SLEEP -m <time in milliseconds>

This is more helpful than TIMEOUT because TIMEOUT can be aborted with a click of a key or CTRL + C (for TIMEOUT /t <secs> /nobreak). SLEEP cannot be aborted by anything (except for close button :p)

Other one is PING. But PING needs internet connection because you'll be recording the connection of a site.

scriptmastere02
  • 357
  • 2
  • 12
  • 2
    There IS a sleep command in vanilla windows. It solely depends on which edition of Windows you're running. This is native to Windows 7 Pro/Enterprise, Windows 10 Pro/Enterprise, All Windows Server 2008+ editions. I have upvoted this as it is a valid solution. – Timothy Wood Jul 31 '18 at 15:33
  • 1
    @TimothyWood I'm running Server 2012 R2 and SLEEP is not available. The answer should provide accurate information on what version(s) of windows it works on. – bobroxsox Aug 08 '18 at 19:50
  • 3
    Some versions that don't have SLEEP available have TIMEOUT available. TIMEOUT /T /NOBREAK – bobroxsox Aug 08 '18 at 19:50
  • 2
    @bobroxsox Sleep is a native command. It just depends on what features and roles you have included in the configuration of your server. To specifically get access to the sleep command, install the 2003 Windows Resource Kit. This automatically installed by enabling one among the few features that require it in the Server Manager. It's also a prerequisite that's included with Visual Studio. The answer was accurate. Not having the sleep command is not the same as not knowing what commands can be used and therefore it's an entirely separate issue. – Timothy Wood Aug 09 '18 at 21:37
  • 2
    Windows 10 has `TIMEOUT` (with the option to shorten the wait by pressing a key, btw), but no `SLEEP` – Frank Nocke Nov 25 '19 at 09:36
10

Two more ways that should work on everything from XP and above:

with w32tm:

w32tm /stripchart /computer:localhost /period:5 /dataonly /samples:2  1>nul 

with typeperf:

typeperf "\System\Processor Queue Length" -si 5 -sc 1 >nul

with mshta (does not require set up network):

start "" /w /b /min mshta "javascript:setTimeout(function(){close();},5000);"
papandreus
  • 314
  • 3
  • 8
npocmaka
  • 51,748
  • 17
  • 123
  • 166
  • 1
    These are tested! Your `TypePerf` and `TYPEPERF` commands work when a network connection is broken. – it3xl Jul 08 '19 at 17:17
9

This is the latest version of what I am using in practice for a ten second pause to see the output when a script finishes.

BEST>@echo done
BEST>@set DelayInSeconds=10
BEST>@rem Use ping to wait
BEST>@ping 192.0.2.0 -n 1 -w %DelayInSeconds%000 > nul

The echo done allows me to see when the script finished and the ping provides the delay. The extra @ signs mean that I see the "done" text and the waiting occurs without me being distracted by their commands.

I have tried the various solutions given here on an XP machine, since the idea was to have a batch file that would run on a variety of machines, and so I picked the XP machine as the environment likely to be the least capable.

GOOD> ping 192.0.2.0 -n 1 -w 3000 > nul

This seemed to give a three second delay as expected. One ping attempt lasting a specified 3 seconds.

BAD> ping -n 5 192.0.2.0 > nul

This took around 10 seconds (not 5). My explanation is that there are 5 ping attempts, each about a second apart, making 4 seconds. And each ping attempt probably lasted around a second making an estimated 9 seconds in total.

BAD> timeout 5
BAD> sleep /w2000
BAD> waitfor /T 180
BAD> choice

Commands not available.

BAD> ping 192.0.2.0 -n 1 -w 10000 > nul :: wait 10000 milliseconds, ie 10 secs

I tried the above too, after reading that comments could be added to BAT files by using two consecutive colons. However the software returned almost instantly. Putting the comment on its own line before the ping worked fine.

GOOD> :: wait 10000 milliseconds, ie 10 secs
GOOD> ping 192.0.2.0 -n 1 -w 10000 > nul

To understand better what ping does in practice, I ran

ping 192.0.2.0 -n 5 -w 5000

This took around 30 seconds, even though 5*5=25. My explanation is that there are 5 ping attempts each lasting 5 seconds, but there is about a 1 second time delay between ping attempts: there is after all little reason to expect a different result if you ping again immediately and it is better to give a network a little time to recover from whatever problem it has had.

Edit: stolen from another post, .. RFC 3330 says the IP address 192.0.2.0 should not appear on the internet, so pinging this address prevents these tests spamming anyone! I have modified the text above accordingly!

Ivan
  • 3,463
  • 28
  • 26
  • 1
    About comments in cmd batch files: Comments should start with the REM command. See https://stackoverflow.com/a/2997627/6838748. The double colon is actually a misused label which is ignored by the command processor. It works as a comment if used on a line of its own, but beware: if used inside IF statements, it will mess up the execution flow. – Wim Oct 18 '19 at 07:55
  • 1
    There are 2 approaches to using the ping command: 1. pinging an existing address (127.0.0.1) or a non-existing one (192.0.2.0). The existing one will reply in less than a millisecond, so you ping n+1 times for an n-second delay. The non-existing one will timeout, so you need to set the timeout value to n*1000 for an n-second delay. – Wim Oct 18 '19 at 08:04
6

I made this. It is working and show time left in seconds. If you want to use it, add to a batch file:

call wait 10

It was working when I tested it.

Listing of wait.bat (it must be in the working directory or windir/system32/):

@echo off

set SW=00

set SW2=00

set /a Sec=%1-1

set il=00
@echo Wait %1 second
for /f "tokens=1,2,3,4 delims=:," %%A in ("%TIME%") do set /a HH=%%A, MM=1%%B-100, SS=1%%C-100, CC=1%%D-100, TBASE=((HH*60+MM)*60+SS)*100+CC, SW=CC 

set /a TFIN=%TBASE%+%100

:ESPERAR
for /f "tokens=1,2,3,4 delims=:," %%A in ("%TIME%") do set /a HH=%%A, MM=1%%B-100, SS=1%%C-100, 

CC=1%%D-100, TACTUAL=((HH*60+MM)*60+SS)*100+CC,  SW2=CC


if %SW2% neq %SW% goto notype
if %il%==0 (echo Left %Sec% second & set /a Sec=sec-1 & set /a il=il+1)
goto no0
:notype
set /a il=0
:no0

if %TACTUAL% lss %TBASE% set /a TACTUAL=%TBASE%+%TACTUAL%
if %TACTUAL% lss %TFIN% goto ESPERAR
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
user1884308
  • 61
  • 1
  • 1
5

An improvement of the code proposed by the user Aacini, It has resolution of hundredths of a second and does not fail when the time reaches 23:59:59,99:

for /f "tokens=1,2,3,4 delims=:," %%A in ("%TIME%") do set /a HH=%%A, MM=1%%B-100, SS=1%%C-100, CC=1%%D-100, TBASE=((HH*60+MM)*60+SS)*100+CC

:: Example delay 1 seg.
set /a TFIN=%TBASE%+100

:ESPERAR
for /f "tokens=1,2,3,4 delims=:," %%A in ("%TIME%") do set /a HH=%%A, MM=1%%B-100, SS=1%%C-100, CC=1%%D-100, TACTUAL=((HH*60+MM)*60+SS)*100+CC

if %TACTUAL% lss %TBASE% set /a TACTUAL=%TBASE%+%TACTUAL%
if %TACTUAL% lss %TFIN% goto ESPERAR
Rober
  • 51
  • 1
  • 1
5

You can use VBScript, for example, file myscript.vbs:

set wsobject = wscript.createobject("wscript.shell")

do while 1=1
    wsobject.run "SnippingTool.exe",0,TRUE
    wscript.sleep 3000
loop

Batch file:

cscript myscript.vbs %1
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Dani
  • 13,366
  • 11
  • 56
  • 99
  • 3
    why the %1? you didn't put any place for arguments in the code. I use this: sleep.vbs: wscript.sleep wscript.arguments(1) – Jeremy Dec 19 '12 at 19:05
4

The easiest way I did it was this:

Download the Sleep.exe at http://www.sleepcmd.com/. The .exe file should be in the same folder as the program you wrote!

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Xavi
  • 107
  • 2
  • 7
  • 10
    if downloading an exe was the right answer, sleep.exe from the ms rk would be a better choice. And putting it in the path. – Jeremy Dec 19 '12 at 19:10
4

It can be done with two simple lines in a batch file: write a temporary .vbs file in the %temp% folder and call it:

echo WScript.Sleep(5000) >"%temp%\sleep.vbs"
cscript "%temp%\sleep.vbs"
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
AjV Jsy
  • 5,161
  • 3
  • 29
  • 30
4

I use the following method entirely based on Windows XP capabilities to do a delay in a batch file:

File DELAY.BAT

@ECHO OFF
REM DELAY seconds

REM GET ENDING SECOND
FOR /F "TOKENS=1-3 DELIMS=:." %%A IN ("%TIME%") DO SET /A H=%%A, M=1%%B%%100,     S=1%%C%%100, ENDING=(H*60+M)*60+S+%1

REM WAIT FOR SUCH A SECOND
:WAIT
FOR /F "TOKENS=1-3 DELIMS=:." %%A IN ("%TIME%") DO SET /A H=%%A, M=1%%B%%100, S=1%%C%%100, CURRENT=(H*60+M)*60+S
IF %CURRENT% LSS %ENDING% GOTO WAIT

You may also insert the day in the calculation so the method also works when the delay interval pass over midnight.

Community
  • 1
  • 1
Aacini
  • 59,374
  • 12
  • 63
  • 94
  • 10
    This is a "busy wait" and so may do undesirable things to your machine's performance. Check task manager while it's running to see effect on CPU usage. – yoyo Jan 22 '14 at 21:23
3
PING -n 60 127.0.0.1>nul

in case your LAN adapter is not available.

Baby Groot
  • 4,609
  • 39
  • 50
  • 67
3

If you have an appropriate version of Windows and the Windows Server 2003 Resource Kit Tools, it includes a sleep command for batch programs. More at: http://malektips.com/xp_dos_0002.html

GreenMatt
  • 16,928
  • 6
  • 49
  • 75
1

In Windows xp sp3 you can use sleep command

Andrés Falcón
  • 253
  • 1
  • 9
  • 1
    I suggest to stop using XP: Extended support for Windows XP ended on April 8, 2014, after which the operating system ceased receiving further support or security updates to most users. As of March 2019, 1.75% of Windows PCs run Windows XP,[7] and the OS is still most popular in some countries with up to 38% of the Windows share.[8] (wikipedia) – Raúl Salinas-Monteagudo Apr 09 '19 at 06:00
1

Make a cmd file called sleep.cmd:

REM Usage: SLEEP Time_in_MiliSECONDS
@ECHO off
ping 1.0.0.0 -n 1 -w %1 > nul

Copy sleep.cmd to c:\windows\system32

Usage:

sleep 500

Sleeps for 0.5 seconds. Arguments in ms. Once copied to System32, can be used everywhere.

EDIT: You should also be away that if the machine isn't connected to a network (say a portable that your using in the subway), the ping trick doesn't really work anymore.

thebunnyrules
  • 1,194
  • 11
  • 19
  • This is a potentially interesting alternative to the other ping examples but you need to explain it more. Why do you choose to ping 1.0.0.0? – Brandin May 15 '17 at 16:12
  • Probably no specific reason. Using 127.0.0.1 is a safer bet as explained in other comments – Tobias Mühl May 16 '17 at 04:20
  • It could be 127.0.0.1. I just choose 1.0.0.0 so if I distribute a batch script, it doesn't look like I'm trying to ping myself if someone reads it. Why is 127.0.0.1 a safer bet? – thebunnyrules May 30 '17 at 18:33
  • why should it not look like you are trying to ping yourself? 1.0.0.0 seems more silly to try to ping.But the more important part is, -w will not have any effect unless you set -n 2. -w specifies wait between packages, and with one package there is no "between" – Plux Aug 16 '17 at 14:03
  • strange, it worked for me without the -n. Though it doesn't seem work if you're running it without being connected to some kind of network. Personally, I don't really use the ping technique to pause anymore because of that reason. As for the address, you can ping whatever you want, it's really not relevant. – thebunnyrules Aug 25 '17 at 00:02
  • Note that there are two ping techniques being used in the replies. Ping a known working address, and ping a known failing address. A single 5 second ping to a failing address e.g. 192.0.2.0 will time for 5 seconds. Alternatively 6 successful pings a second apart to a working address e.g. 127.0.0.1 will time for 5 seconds plus the length of the 6 pings.I think there is confusion about the two techniques in the comments above. – Ivan Jun 19 '19 at 11:40
0

Well this works if you have choice or ping.

@echo off
echo.
if "%1"=="" goto askq
if "%1"=="/?" goto help
if /i "%1"=="/h" goto help
if %1 GTR 0 if %1 LEQ 9999 if /i "%2"=="/q" set ans1=%1& goto quiet
if %1 GTR 0 if %1 LEQ 9999 set ans1=%1& goto breakout
if %1 LEQ 0 echo %1 is not a valid number & goto help
if not "%1"=="" echo.&echo "%1" is a bad parameter & goto help
goto end

:help
echo SLEEP runs interactively (by itself) or with parameters (sleep # /q )
echo where # is in seconds, ranges from 1 - 9999
echo Use optional parameter /q to suppress standard output 
echo or type /h or /? for this help file
echo.
goto end

:askq
set /p ans1=How many seconds to sleep? ^<1-9999^> 
echo.
if "%ans1%"=="" goto askq
if %ans1% GTR 0 if %ans1% LEQ 9999 goto breakout
goto askq

:quiet
choice /n /t %ans1% /d n > nul
if errorlevel 1 ping 1.1.1.1 -n 1 -w %ans1%000 > nul
goto end

:breakout
choice /n /t %ans1% /d n > nul
if errorlevel 1 ping 1.1.1.1 -n 1 -w %ans1%000 > nul
echo Slept %ans1% second^(s^)
echo.

:end

just name it sleep.cmd or sleep.bat and run it

Doctor DOS
  • 243
  • 1
  • 2
  • 10
0

ping waits for about 5 seconds before timing out, not 1 second as was stated above. That is, unless you tell it to only wait for 1 second before timing out.

ping 1.0.0.1 -n 1 -w 1000

will ping once, wait only 1 second (1000 ms) for a response, then time out.

So an approximately 20-second delay would be:

ping 1.0.0.1 -n 20 -w 1000

LionelGoulet
  • 479
  • 2
  • 13
  • The accepted answer describes it already, and Jonathan already showed your solution of using an invalid IP address – jeb Jan 26 '16 at 23:49
  • Also, if the pings last a second (waiting for a response that doesn't happen) and are a second apart - as there is no point repeating a failure immediately - then your approximate 20 second delay will be closer to 39 seconds. By copying the accepted answer, you also copy its mistakes! – Ivan Dec 01 '17 at 10:01
  • The current time is: 10:00:03.80 (RUN YOUR 20 SECOND DELAY) The current time is: 10:00:45.96 That's not what I call a 20s delay! – Ivan Dec 01 '17 at 10:03
0

I wrote a powerbasic program wait.exe, where you pass a millisecond parameter to it in your batch file

wait 3000
system('c:/windows/system32/SnippingTool.exe')

the code for the EXE:

FUNCTION PBMAIN()
  c$ = Command$
  s! = Val(c$)*1000
  Sleep s!         
END FUNCTION
Shawn
  • 2,624
  • 3
  • 22
  • 46
-1

On newer Windows OS versions you can use the command

sleep /w2000

in a DOS script (.cmd or .bat) to wait for 2s (2000 ms - substitute the time in ms you need). Be careful to include the /w argument - without it the whole computer is put to sleep! You can use -m instead of /m if you wish and optionally a colon (:) between the w and the number.

jvallver
  • 1,594
  • 1
  • 8
  • 19
jon
  • 15
  • 1
-1

This should do the trick: choice /T 5 /N /D Y

Replace the 5 with the time in seconds you want to wait...

Smits
  • 37
-4

I think the following command can help:

pause 5

The syntax of the pause command is: pause d \\where d represents the duration in seconds

I am using Windows 7 (32 bit), but I don't know about the others.

  • 5
    On WinXP is does not work like that. It waits for infinity, ignoring the argument. – dma_k Apr 04 '13 at 16:04
  • 5
    The purpose of pause is to, "Suspends processing of a batch program and displays the message Press any key to continue . . ." – Atiq Rahman Aug 17 '13 at 08:55
  • Nope, not on win 7, you must have some non-standard utilities installed. – yoyo Jan 22 '14 at 21:25
  • Available on all Windows releases according to http://www.computerhope.com/pausehlp.htm. Note thought it is not available on command-line, only inside batch files.. – grtjn May 21 '16 at 19:05