Tuesday, 6 March 2012

How to add a sleep function to an HTA

The WScript.Sleep function in VBScript is useful. However, when you decide to use HTA to provide an interface to your script, the sleep function become a problem as you can't use WScript functions in HTA.


For the WScript.Echo, you can use MsgBox, however, there is no equivalent for the WScript.Sleep.


You could do it using a loop, that's working but it's resource intensive. You could also create a VBScript file on the fly where you include the WScript.Sleep command and run it via the HTA but there is an easier, faster and quite efficient solution. 
So, here is an option that I used several times which did the trick for me.

In the following example, the sbWait sub is run a command line to do a ping to the localhost IP address for the number of times of your choice. Because each ping request is done every second, you just have to mention using the iSeconds variable the number of time you want to do it.

Enjoy.

<html>
<head>
<title>Simple HTA</title>
<HTA:APPLICATION
     ID="oSimpleHTA"
     APPLICATIONNAME="SimpleHTA"
>
</head>
<script Language="VBScript">
Sub Window_Onload
    dataarea.innerhtml = "<p>This is a simple HTA</p>"
    dataarea.innerhtml = "<p>Let's wait for 5 seconds</p>"
    sbWait(5)
    dataarea.innerhtml = "<p>Done.</p>"
End Sub
Sub sbWait(iSeconds)
    Dim oShell  : Set oShell = CreateObject("WScript.Shell")
    oShell.run "cmd /c ping localhost -n " & iSeconds,0,True
End Sub
</script>
<body>
    <h1>Simple HTA</h1>
    <span id="dataarea"></span>
</body>
</html>

3 comments:

  1. Better:

    Sub sbWait(iMilliSeconds)
         Dim oShell : Set oShell = CreateObject("WScript.Shell")
         oShell.run "cmd /c ping localhost -n 1 - w " & iMilliSeconds,0,True
    End Sub

    Allows you to specify wait times in milliseconds, by waiting for a single ping with a timeout you specify.

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
    Replies
    1. The blog is also quite difficult to read. :(

      Delete