views:

379

answers:

3

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 suddently 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?

A: 

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?

Rex M
I realised i was in effect answering a completely different question in my original answer (since deleted), then i started to write a new answer and then realised i was just writing what you said, but differently :DGo me!
olliej
The alert won't happen; I can wait as long as I like (I waited 20+ minutes) and the alert didn't show until a few seconds after I clicked around in the window.The thread was created in the extension (pthread) and it tries to use the callback. If I do work in the callback, crash. So I do setTimeout.
Paul
A: 

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...

Paul
A: 

Did you try https://developer.mozilla.org/en/nsISupports_proxies?

Nickolay