Search code examples
batch-filetime-wait

Milliseconds (!) wait in Batch using no externals?


I have searched intensively but have only found wait-tips in batch files in seconds units (the ping approach i.e.).

Since I have a need to wait in between two commands only for something like 10-100 milliseconds, that does not work for me unfortunately.

The wait-time needs not to be "super accurate". In my case, does not make a big difference if it's 10ms or 12/15ms, but it should be able to distinguish between 10 and, say 20.

I wonder if there is a solution, and if in any way possible, using just the windows "on board" commands / tricks as I want to have just the batch for ease of "installation" when using later on another machine.


Solution

  • @echo off
    
    echo Time before: %time%
    echo Wait %1 centiseconds (or more)
    call :wait %1
    echo Time after:  %time%
    goto :EOF
    
    :wait centiseconds
    for /F "tokens=3,4 delims=:." %%a in ("%time%") do set /A sec=1%%a, msec=1%%b+%1
    if %msec% gtr 199 set /A sec+=1, msec-=100
    set lim=%sec%%msec%
    :waitHere
    for /F "tokens=3,4 delims=:." %%a in ("%time%") do if 1%%a1%%b lss %lim% goto waitHere
    exit /B
    

    The minimum precise wait time entirely depends on the speed of the computer. For example, in my case a wait time less than 5 centiseconds always waits for more time. If I use a wait time from 5 centiseconds on, the timing is precise.

    EDIT: I slightly modified the program in order to make it more precise with small wait times, it is now precise in my computer from 3 centiseconds on!

    You must note that the minimum precise wait time also depends on the size of the Batch file; if the file is large, the minimum precise time increases...