How does #onmessage and #postmessage work to communicate between main thread and HTML5's webworkers?

前端 未结 1 1033
清歌不尽
清歌不尽 2021-01-25 18:48

I\"m learning about HTML5 workers from here and the author uses self.onmessage and self.postmessage to communicate between the main thread and the work

相关标签:
1条回答
  • 2021-01-25 19:39

    in your file worker.js think of the self.postMessage as the order/instruction that the worker (self) should post a message. Since it is only able to communicate with the mainJS which created it, this message goes there. :) Also in your mainJS worker.onmessage should be understood as the event "a message comes from the worker".

    So basically you have both options in both your scripts: in mainJS: worker.postMessage("message"); to send a message to the worker - and worker.onmessage = function(event){...} to listen to messages from the worker

    in worker script: (self or) this.onmessage = function(event){...} to listen to messages from the mainJS - and self.postMessage("message"); to send something back to mainJS

    0 讨论(0)
提交回复
热议问题