Tips, tricks, techniques, tools, and code for those who administer Windows desktops.

VBScript Sleep Function

Occasionally, it is helpful to have a VBScript you are running pause for a moment.  Maybe you need to have it wait for something to finish.  Maybe you’re just pausing to give the human user a chance to look at the output on the screen.  Whatever the reason, you’d like the script to stop in its tracks for a few seconds.  This code will help you do that.

Versions of the VBScript engine that are 5.1 or later (which is generally XP and above) will work without this code, by simply calling “wscript.sleep” followed by the number of milliseconds to sleep.  For instance, “wscript.sleep 2000″ will sleep for 2 seconds.

The VBScript sleep example below was originally written for an environment where Windows 9x and XP were in use, so it needed to identify the VBScript version and behave accordingly.  Where the script host version was too old, it didn’t attempt to use the built-in VBScript sleep command but instead used a loop that timed out when the desired number of seconds had passed.

' The MySleep function is designed to cause the script
' to pause for the specified number of seconds to allow
' a parallel process to complete, etc.
'
' It checks for the presence of the built-in WSH sleep
' function and uses that if available.  Otherwise it
' uses its own method to sleep.
'
Function MySleep(seconds)
   wsv = WScript.Version
   if wsv >= "5.1" then
      WScript.Sleep(seconds * 1000)
   else
     elapsed = TimeSerial(0,0,seconds)
     startTime = Time()
     endTime = TimeValue(startTime) + TimeValue(elapsed)
     While endTime > Time()
         '
     Wend
   end if
End Function
Enhanced by Zemanta

Sponsored Links