Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I pass parameters to .js function when I create the new Web Workers object?

When I create a web workers like the following...

 var w = new Worker("./Scripts/sample.js");

sample.js want to some parameters from the caller!!
Possible?

like image 878
Nigiri Avatar asked Sep 12 '12 05:09

Nigiri


People also ask

Can I pass function to web worker?

Limitations of Web Workers worker. postMessage({ string: 'string', number: 0, array: [], ... }); Those value types above can be handled by the structured cloning. However, you cannot send in functions because they can be neither cloned nor transferred.

What are the limitations of web workers?

Limitations Of Web WorkersA worker can't directly manipulate the DOM and has limited access to methods and properties of the window object. A worker can not be run directly from the filesystem. It can only be run via a server.

Which JavaScript method is used to instantiate a web worker?

You need to use the postMessage() method in the onmessage event handler in worker. js : // src/worker. js onmessage = e => { const message = e.

Where should you place JavaScript code to run in the context of a web worker?

You can run whatever code you like inside the worker thread, with some exceptions. For example, you can't directly manipulate the DOM from inside a worker, or use some default methods and properties of the window object.


1 Answers

I haven't used web workers a whole bunch, but per this description I believe you could do it along these lines:

var worker = new Worker("sample.js");
worker.postMessage({ "args": [ ] });

Then, in sample.js, structure it along these lines:

self.addEventListener("message", function(e) {
  var args = e.data.args;
  // do whatever you need with the arguments
}, false);

This isn't quite the same as a traditional argument passing, as whatever goes in postMessage must be formattable as a JSON (e.g. no functions). But, there's a decent chance it can be made to do what you need it to do.

like image 144
Bubbles Avatar answered Sep 18 '22 15:09

Bubbles