Sign in to follow this  
JohnnyCode

Totaly misunderstanding JS webworker object

Recommended Posts

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

Edited by jbadams
Post contents restored from history.

Share this post


Link to post
Share on other sites

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

Share this post


Link to post
Share on other sites

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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this