VBScript Scripting Techniques > Time & Date > 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, would you?
You can use the
setTimeout
and
clearTimeout
methods in HTAs, but 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 (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
Set wshShell = CreateObject( "WScript.Shell" )
wshShell.Run "ping -n " & ( seconds + 1 ) & " 127.0.0.1", 0, True
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.