How to implement a recursive function as a Web Worker?

北慕城南 提交于 2019-12-11 02:42:26

问题


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/



来源:https://stackoverflow.com/questions/21831298/how-to-implement-a-recursive-function-as-a-web-worker

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!