How to implement a recursive function as a Web Wor

2019-07-16 18:34发布

问题:

Here is a setup:

  1. A big data array to be processed in recursive function.
  2. A recursive function itself, which is running as Web Worker to avoid stack size limitations.
  3. A result processor, which is called after recursive function reached it's 'end of recursion' condition.

I've checked web worker specs, but they are kinda unreadable and messy to give a simple answer on simple question.

What I do not understand it's

  1. How to pass data to function (in web worker)
  2. How to get result from function and know when it's done
  3. And why I have to define worker in separate JS file

回答1:

As mentioned by Bergi, you pass data to and from your web workers using events.

Regarding #3 - There's a concept of "inlined workers", where you create a blob object, and then from that, create a url object. Something like:

var blobURL = URL.createObjectURL( new Blob([ '(',
    function(){
        self.addEventListener('message', function (e){
            // Do stuff with array here
        }.toString(),
    ')()' ], { type: 'application/javascript' } ) ),

worker = new Worker( blobURL );

worker.postMessage(/* big array */);

You can find some information regarding inline workers here:

http://www.html5rocks.com/en/tutorials/workers/basics/#toc-inlineworkers

I threw together this fiddle with an inlined web worker and a (simple) recursive function: http://jsfiddle.net/tQcuy/