The worker feature


Note: if you want the worker feature, you must either use the "Whole 9 Yards" release of hyperscript, or include the /dist/workers.js file.


worker <worker-name>[(<external-scripts>)] <worker-body> end


_hyperscript allows you to create Web Workers whose functions are exposed to the main thread.

worker Incrementer
    function _increment(n) { return n + 1 }
  def increment(n) return _increment(n) end

Any function declarations (declared with def) will be exposed on the main thread, so the above worker can be invoked as Incrementer.increment(4) in either _hyperscript or JavaScript. The body of the function will then run in the worker and the result returned asynchronously to the main thread. As a result, the worker feature can be used to perform calculations in a non-blocking way, and although these worker functions return promises, _hyperscript's [async-transparent] nature means we can call it as if it were synchronous. In summary:

Because it runs in a Web Worker, the code inside a worker body cannot access the DOM or the window global scope. It also can't access scripts included in the main thread, which is what the external-scripts feature is for. URLs passed in as external scripts, if relative, need to be relative to the HTML document which spawns the worker.


Run CPU-heavy operations in a worker

<script type="text/hyperscript">
  worker Miner("/scripts/mine-crypto.js")
  		var miner = new CryptoMiner();
  		return { miner }

  	def startMining() miner.start() end
  	def stopMining() miner.stop() end

    _="on change
                            if me.checked Miner.startMining()
                            else Miner.stopMining()"
  Disable ads <small>and enable cryptocurrency mining</small>