Pausing a Batch Script for a Given Time

Here is another piece of code which I found today.

As you all know Windows sucks when it comes to shell/batch scripting (well not just there, but that’s another story) and so even basic things become difficult.

For example there is no easy way to pause a script for a given time (sleep(1) on Unix), but with the help of the ping command this can be achieved.

There are different ways to accomplish this first one is not that good because it causes some network traffic but on the other hand the time interval is highly configurable. It works by sending a ping request to an IP address which isn’t reachable, and then waits the required time (in milliseconds) before continuing.

::
:: wait 10 seconds
::

ping 0.0.0.0 -n 1 -w 10000 > NUL

If this exact timing is not necessary there is another somewhat cleaner method which sends a given number of ICMP packets to localhost. The time used for doing this is about ~1s per package.

ping -n 10 localhost > NUL

With this and another trick it is even possible to create a minimalist progress bar.

@echo off

For /L %%I in (1,1,10) Do (
  (Set /P i=#) < NUL
     ping localhost -n 2 > NUL)