WLJS LogoWLJS Notebook

Async

Utils

SetTimeout

Spawns an asynchronous task (a wrapper over ScheduledTask) that evaluates an expression once.

SetTimeout[expr_, interval_Real | interval_Quantity] _TaskObject

This symbol has the HoldFirst attribute. The interval is specified in milliseconds or as a Quantity object. To cancel it, use:

CancelTimeout[_TaskObject]

SetInterval

Spawns an asynchronous task (a wrapper over ScheduledTask) that evaluates an expression every interval milliseconds.

SetInterval[expr_, interval_Real | interval_Quantity] _TaskObject

This symbol has the HoldFirst attribute. To cancel this task, use:

TaskRemove[_TaskObject]

or

CancelInterval[_TaskObject]

PauseAsync

Works similarly to Pause, but returns a Promise.

Then[PauseAsync[3], Beep];

TableAsync

Works similarly to Table, but the inner expression can be an implicit AsyncFunction.

n = EvaluationCell[];

TableAsync[
  PauseAsync[1] // Await;
  i
, {i,3}] // WaitAll

DoAsync

Works in the same way as TableAsync.

More

There are more expressions in the standard library that support async programming patterns:

Asynchronous Functions

AsyncFunction

Works similarly to Function.

AsyncFunction[args, body] _Promise

You can use it as a normal function while utilizing the Await keyword. Behind the scenes, it restructures the body at runtime.

Await

Pauses execution (non-blocking to threads) until the promise is resolved and returns the result.

Await[_ | _Promise] _

If the argument is not a Promise, execution continues without pausing and the argument is returned unchanged.

Supported expressions:

  • Set
  • CompoundExpression
  • If
  • Module, With
  • _Symbol or any other singular expressions
  • TableAsync
  • DoAsync
  • PauseAsync
  • Any expression that returns Promise or EventObject

Not yet supported:

  • Loops: While, For, Do
  • Await inside the first argument of With
  • Tables and maps: Map, Table
  • Return does not work correctly inside AsyncFunction

For example:

btn = InputButton[]

Then[AsyncFunction[x, Module[{res},
  Speak["Click to start"];
  btn // Await;
  Speak["Choose"];
  res = ChoiceDialogAsync["Add 10?"] // Await;
  If[res, x + 10, x] 
]][10], Speak];

On this page