3

Imagine you have a simple function in Windows Script Host (JScript) environment:

function say(text) {
    WScript.Sleep(5000);
    WScript.Echo(text);
}

Is it possible to call say() asynchronously?

Note: Such browser-based methods as setInterval() or setTimeout are not available in WSH.

ruvim
  • 7,151
  • 2
  • 27
  • 36
  • 1
    Closely related: http://stackoverflow.com/questions/2198449/settimeout-not-working-in-windows-script-jscript/2655180#2655180 But people searching aren't going to find that one, they'll find this one. – T.J. Crowder Dec 14 '10 at 14:33

2 Answers2

3

No, Windows Script Host doesn't support calling script functions asynchronously. You'll have to run two scripts simultaneously to achieve this effect:

// [main.js]
var oShell = new ActiveXObject("WScript.Shell");
oShell.Run(WScript.FullName + " say.js Hello");

WScript.Echo("Hello from main");

 

// [say.js]
WScript.Sleep(5000);
WScript.Echo(WScript.Arguments.Item(0));
Helen
  • 87,344
  • 17
  • 243
  • 314
2

As far as I know, there is no equivalent to setTimeout / setInterval under Windows Script Host (shockingly). However, you may find this simple function queue in another answer here on SO a useful starting point for emulating it. Basically what the guy did (his name is also "TJ", but it's not me) was create a function queue, and then you call its main loop as your main method. The main loop emulates the heartbeat in browser-based implementations. Quite clever, though I'd change the naming a bit.

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Unfortunately, this is not what I need. The problem is that real parallelism (thread emulation) is required because of heavy calculations are made in `say()` method. – Savva Mikhalevski Dec 14 '10 at 14:49
  • 2
    @Savva: Yeah, you're not going to get that purely with WSH + JScript (and you wouldn't with a browser + JavaScript, either; `setTimeout` doesn't set up parallelism, just deferred-execution). You can use `WshScriptExec` [http://msdn.microsoft.com/en-us/library/2f38xsxe(v=VS.85).aspx] to fire up multiple scripts, which can interact via `StdIn` and `StdOut`. – T.J. Crowder Dec 14 '10 at 18:11