Sleep routine for HTA scripts

iRon picture iRon · May 31, 2013 · Viewed 11.7k times · Source

In several of my .HTA scripts that I created, I had the need for the VBScript WScript.Sleep command which simply waits for a number of milliseconds without utilizing the CPU. And when I browse the web, it appears that I am not the only one looking for this:

https://www.google.nl/search?q=hta+sleep

(I bet that if you read this, you probably need(ed) this as well)

The best solution that I could find appears to be the one which uses the PING command. But especially for a situation were just need to pause the script for a few 100ms, this solution is quiet odd as it uses an external command and triggers all kind of (network) processes that unlikely have anything to do with the concerned .HTA script.

So the first thing that came to my mind was to use the WMI Win32_PingStatus class to avoid the external command but then I started to question why not completely basing it on WMI. It has taken me several hours to get the right WMI classes and methods in place, but finally I succeeded…

Answer

Stephen Quan picture Stephen Quan · Feb 11, 2015

When writing HTA's you should be thinking asynchronously. Consider rewriting your code to use window.setTimeout. In the following example, I will use window.setTimeout to make a bell sound every 2 seconds:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="x-ua-compatible" content="ie=8">
<title>Bell Test</title>
<script language="VBScript">
Option Explicit
Dim objWShell
Set objWShell = CreateObject("WScript.Shell")
Sub DoPing
    divText.innerText = Now
    objWShell.Run "%COMSPEC% /c ECHO " & Chr(7), 0, False
    window.setTimeOut "DoPing", 2000
End Sub
Sub window_OnLoad
   window.ResizeTo 240,130
   DoPing
End Sub
</script>
</head>
<body>
<div id="divText">TEST</div>
</body>
</html>