Spin event loop in ChromeWorker

Hi all,
In the main thread, I can spin the loop with the not recommended nsiThread however I don’t need this. I need to spin the loop in a ChromeWorker. I have dispatched an async method and want to wait for it to complete. I know Task.jsm is a solution but I can’t do that without reworking this chunk of code.

Is there anyway to spin the event loop?

I tried this and it obviously didn’t wok, as it was in the while loop forever:

    var lang = fetchFilestoreEntry({ mainkey:'prefs', key:'default_tesseract_lang' }); // <<<<<<< this call is async
    var st = Date.now();
    var i = 0;
    while (!gFilestoreDefault.prefs.quick_save_dir) {
        i++;
    }
    var end = Date.now();
    console.log('prefs__quick_save_dir: took this long to get quick save dir:', (end - st), 'ms', 'ticks:', i);

This would get stuck in the while loop forever.

1 Like

I assume there is a reason why you are not using callbacks/Promises or at least a setTimeout loop?

Active waiting will/should never work in JavaScript (it would imply race conditions)

Thanks NilkasG for the reply, I plan to switch to promise but its a old and large piece of sync code I need to get in right now. :frowning:

Well, If you want to do something like active waiting (and have a setTimeout function):

const isDone = () => false; // your condition here
const period = 100; // choose whatever seems appropriate
(function poll() {
    isDone() ? whenDone() : setTimeout(poll, period);
})();
function whenDone() {
    // async operation done
}

Thanks that’s a good idea, but I need to hold it from returning. I can pull this off with a ctypes call to SleepEx on Windows (I didn’t test other platforms yet), but I was hoping to avoid ctypes haha.

const isDone = () => false; // your condition here
const period = 100; // choose whatever seems appropriate
   function poll() {
    while(true) {
         isDone() ? break : SleepEx(period);
    }
    return isDone();
}

var rez = poll();

That’s some really nasty JavaScript, but I think you know that …

I think if you use Task.js, you don’t have to change that much of your code.
EDIT: Oh, you realized that yourself.

Haha. I think I might just take the a week sometme and rewrite this crap! I really appreciate your replie!

Sleep is better, otherwise you’ll be hogging a CPU. Whose idea was it to add threads to javascript without adding a sleep function?

1 Like

You could experiment with httpd.js and synchronous XHR. It is the only non-ctypes way I’m aware of to cause sleep in workers.

Thanks Litho for that sentiment! I agree I like to use sleep in my threads.

Oh wow that’s a great idea I will definitely toy with this and let you know how it goes!