Experiment 02 · Async Generators · Single worker

Three async range( min, max, step, delay) generator functions run in parallel and in background.
The delay determines the time to wait, in milliseconds, before each one returns its next value.

const worker = new Worker( "worker.js");
worker.postMessage( { name: "range+050", op: "range", args: [ 0, 50, 10 ] });
worker.postMessage( { name: "range+200", op: "range", args: [ 100, 200, 10, 100 ] });
worker.postMessage( { name: "range-200", op: "range", args: [ -100, -200, -10, 400 ] });
worker.postMessage( { name: "namedOp01", op: "sip", args: [ "☕️" ] });
worker.postMessage( { name: "namedOp02", op: "crunch", args: [ "🍐", "🍪" ] });

Observe that each call to postMessage() automatically spawns an independent background execution — by the virtue of the event-model used to communicate with Web Workers — and that the results of each range are delivered interleaved, not in the exact same sequence as the postMessage() calls.

Note: in the results hereafter, the time elapsed since inception of the Web Worker is displayed to the left, in milliseconds. Execution of the Web Worker is terminated after a timeout of 6000ms, to avoid infinite execution (changing step to zero, for instance, would produce an infinite range of the same value).

Supported by Safari 12 and Firefox 64 and Chrome 71 out-of-the box.