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: I found that a quick-and-dirty batch command is the safest and surest (though not the most accurate) way to get a delay.

' Get a 10 seconds delay
Delay 10

Sub Delay( seconds )
	Dim wshShell, strCmd
	Set wshShell = CreateObject( "WScript.Shell" )
	strCmd = "%COMSPEC% /C (PING -n " & ( seconds + 1 ) & " 127.0.0.1 >NUL 2>&1 || PING -n " & seconds & " ::1 >NUL 2>&1)"
	wshShell.Run strCmd, 0, 1
	Set wshShell = Nothing
End Sub
Note: Back in the IPv4-only era, the command would have been a lot easier on the eyes, but this command line takes into account both IPv4 and IPv6.

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 uploaded: 2016-09-19, 14:58