Totaly misunderstanding JS webworker object

Started by
3 comments, last by jbadams 10 years, 8 months ago

I have quite a problem with understanging WebWorker object in JS.

var webworker= new Worker('WI.js');

webworker.onmessage = function(e) { alert(e.data); };

webworker.postMessage('s'); // nothing is done, s is not alerted

the WI.js file is:

postMessage('t');

//self.postMessage('some');

What happens with this code is that I get an alert of t, not s. Bad thing is that I get an alert of t even if I comment webworker.postMessage('s');

Does it mean that WI.js is run at var webworker= new Worker('WI.js');?

If I uncomment second line in WI.js, I get alert 'some' and then alert 't', while I have webworker.postMessage('s'); still commented out.. I am so confused.If I write webworker.postMessage('s'); 4 times or 0 times, makes no difference and I get 'bn' then 't' and then nothing. I am so confused. How do I actualy invoke webworker correctly from main thread, and message something from webworker back?

Thanks a lot

Advertisement

Please don't do that. If you have a problem and you find the solution, please post it so other people who might have the same problem can find the answer.

if you think programming is like sex, you probably haven't done much of either.-------------- - capn_midnight

Please don't remove your posts after finding a solution -- I've restored the original contents of your post -- if you managed to solve your own problem, perhaps you could share what you learned to help others who may experience the same problem in future. smile.png

- Jason Astle-Adams

The way it works is :

Wi.js is run at web worker instancing. Thus, it is apropriate to assig even handler in the Wi.js like this:

Wi.js:

self.onmessage = function(e) {
self.postMessage('you sent from main thread '+e.data);
ComputeSomeStuff();
};

then, if you write this in main thread:

var webworker= new Worker('WI.js');
webworker.postMessage('run');

you have just invoked COmputesomestuff(), but you will not recieve the "you sent from main thread run" message for you have not establshed event handler on the webworker yet. If you want to have webworker signalize thing back, you must do so like this.

var webworker= new Worker('WI.js');

webworker.onmessage = function(e) {
alert(e.data);
};

webworker.postMessage('run'); // alert of "you sent from main thread run" will appear while ComputeSomeStuff() is running

The reason I edited post is that the question was about understanding the concept, and since I found it out, I did not know how to reply actualy, other than writing a micro tutorial like this. Sorry.

Thanks for sharing what you learned Johnny! smile.png

- Jason Astle-Adams

This topic is closed to new replies.

Advertisement