Rob van der Woude's Scripting Pages

VBScript Scripting Techniques > Time & Date > Delays

Delays

I often need delays in my scripts, e.g. to wait for an object or a connection to get ready.

The easiest way to implement a 1 second delay, of course, is WSH's WScript.Sleep 1000 (delay in milliseconds).

Dim objIE
' Create an IE object
Set objIE = CreateObject( "InternetExplorer.Application" )
objIE.Navigate "about:blank"
' Wait till IE is ready
Do While objIE.Busy
	WScript.Sleep 1000
Loop

That's fine for scripts running in CSCRIPT.EXE or WSCRIPT.EXE, but in HTAs or WSCs there is no WScript object, and thus no WScript.Sleep, so we need an alternative.

A quick-and-really-dirty way is just remove the WScript.Sleep line:

Dim objIE
' Create an IE object
Set objIE = CreateObject( "InternetExplorer.Application" )
objIE.Navigate "about:blank"
' Wait till IE is ready
Do While objIE.Busy
Loop

This will work, but the script will loop hundreds of times per second, and you'll see your CPU usage remain at 100% until the script exits the loop.
That may sometimes be acceptable, e.g. in a login script when no time critical processes are running, but you wouldn't want to run a script like that while burning a CD or watching a HD video on YouTube, would you?

You can use the setTimeout and clearTimeout methods in HTAs, well explained in this Scripting Guys article.
However, that will start a command in a separate process, while the script itself continues and won't wait for the command to finish (more or less like the START command in batch files, with an added time delay).
This may work in some cases, but it isn't always practical, as you will need to split the code at the delay (try to use it within a loop and it's really going to look messy).

While on the subject of batch commands: you can "embed" a batch command in your VBScript code to get a delay in Windows 7 and later versions:

' Get a 10 seconds delay
Delay 10

Sub Delay( seconds )
	Dim wshShell, strCmd
	Set wshShell = CreateObject( "WScript.Shell" )
	strCmd = wshShell.ExpandEnvironmentStrings( "%COMSPEC% /C (TIMEOUT.EXE /T " & seconds & " /NOBREAK)" )
	wshShell.Run strCmd, 0, 1
	Set wshShell = Nothing
End Sub

Using TIMEOUT is a lot more reliable than the old PING trick — which does work in older Windows versions, though, as long as it supports TCP/IP:

' Get a 10 seconds delay
Delay 10

Sub Delay( seconds )
	Dim wshShell, strCmd
	Set wshShell = CreateObject( "WScript.Shell" )
	strCmd = wshShell.ExpandEnvironmentStrings( "%COMSPEC% /C (PING.EXE -n " & ( seconds + 1 ) & " localhost >NUL 2>&1)" )
	wshShell.Run strCmd, 0, 1
	Set wshShell = Nothing
End Sub

This will work in HTAs and WSCs, as well as in WSCRIPT.EXE/CSCRIPT.EXE (though in the latter, WScript.Sleep is a much better choice, of course).

See my Wait page for a detailed explanation of time delays with the PING command.


page last modified: 2017-09-01; loaded in 0.0012 seconds