We can use the web worker in HTML5 like this:
var worker = new Worker('worker.js');
but why can't we call a function like this?
var worker = new Worker(function(){
//do something
});
We can use the web worker in HTML5 like this:
var worker = new Worker('worker.js');
but why can't we call a function like this?
var worker = new Worker(function(){
//do something
});
By design web workers are multi-threaded, javascript is single threaded"
*"multiple scripts cannot run at the same time.
refer to: http://www.html5rocks.com/en/tutorials/workers/basics/
This answer might be a bit late, but I wrote a library to simplify the usage of web workers and it might suit OP's need. Check it out: https://github.com/derekchiang/simple-worker
It allows you to do something like:
Just use my tiny plugin https://github.com/zevero/worker-create
and do
This is the way web workers are designed. They must have their own external JS file and their own environment initialized by that file. They cannot share an environment with your regular global JS space for multi-threading conflict reasons.
One reason that web workers are not allowed direct access to your global variables is that it would require thread synchronization between the two environments which is not something that is available (and it would seriously complicate things). When web workers have their own separate global variables, they cannot mess with the main JS thread except through the messaging queue which is properly synchronized with the main JS thread.
Perhaps someday, more advanced JS programmers will be able to use traditional thread synchronization techniques to share access to common variables, but for now all communication between the two threads must go through the message queue and the web worker cannot have access to the main Javascript thread's environment.
While it's not optimal and it's been mentioned in the comments, an external file is not needed if your browser supports blobURLs for Web Workers. HTML5Rocks was the inspiration for my code:
Caveats:
The blob workers will not successfully use relative URLs. HTML5Rocks link covers this but it was not part of the original question.
People have reported problems using Blob URLs with Web Workers. I've tried it with IE11 (whatever shipped with FCU), MS Edge 41.16299 (Fall Creator's Update), Firefox 57, and Chrome 62. No clue as to Safari support. The ones I've tested have worked.
Note that "sample" and "sample_dependency" references in the Blob constructor call implicitly call
Function.prototype.toString()
assample.toString()
andsample_dependency.toString()
, which is very different than callingtoString(sample)
andtoString(sample_dependency)
.Posted this because it's the first stackoverflow that came up when searching for how to use Web Workers without requesting an additional file.
Took a look at Zevero's answer and the code in his repo appears similar. If you prefer a clean wrapper, this is approximately what his code does.
Lastly -- I'm a noob here so any/all corrections are appreciated.
WebWorkers Essentials
WebWorkers are executed in an independent thread, so have no access to the main thread, where you declare them (and viceversa). The resulting scope is isolated, and restricted. That's why, you can't , for example, reach the DOM from inside the worker.
Communication with WebWorkers
Because communication betwen threads is neccessary, there are mechanisms to accomplish it. The standard communication mechanism is through messages, using the worker.postMessage() function and the worker.onMessage(), event handler.
More advanced techniques are available, involving sharedArrayBuffers, but is not my objective to cover them. If you are interested in them, read here.
Threaded Functions
That's what the standard brings us. However, ES6 provides us enough tools, to implement an on-demmand callable Threaded-Function.
Since you can build a Worker from a Blob, and your Function can be converted into it (using URL.createObjectURL), you only need to implement some kind of Communication Layer in both threads, to handle the messages for you, and obtain a natural interaction.
Promises of course, are your friend, considering that everything will happen asynchronously.
Applying this theory, you can implement easilly, the scenario you describe.
My personal approach : ParallelFunction
I've recently implemented and publised a tiny library wich does exactly what you describe. in less than 2KB (minified).
It's called ParallelFunction, and it's available in github, npm , and a couple of CDNs.
As you can see, it totally matches your request:
After initialization, you can call your function as many times you need. a Promise will be returned, wich will resolve, when your function finishes execution.
By the way, many other Libraries exists.