简体   繁体   中英

How do I communicate between threads in JavaScript?

I created an XPCOM object in C++ for a FireFox extension. I'm using a worker thread to listen for an event and when it happens, I need to do stuff on the main thread. Obviously, I can't just sit and wait in JavaScript on the main thread because you need to be able to use the browser (my event happens very rarely).

I tried doing this in the thread (xpcom guy sends javascript an event):

window.setTimeout( myImportantWorkFunction, 100 );

This works (on the main thread, as intended), but it will pause indefinately. it doesn't happen after 100ms as intended. You have to click around a bit or resize the window and then suddenly the function gets called. Like JavaScript suddenly woke up. I assume this is because it's happening in a thread.

Is there some better way for the worker to ask the main thread to do something?

JavaScript only has one thread. Function calls always block until they return. If you are communicating from JS to the browser (or extension of the browser in this case), you should make sure your browser-side code returns to the JS immediately, and remember a callback to invoke when your work completes (this is how setTimeout works).

I suspect the "clicking around" is just a coincidence. Have you tried alerting as soon as the event is fired?

For those that care, I gave up on trying to message between threads. I found a way to compile the XPCOM object with some objective-C++ so that I could use their NSDistributedNotificationCenter. This lets me get my event on the main thread where javascript is happy.

The question is still valid but I probably won't take the time to validate anybody's answer now...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM