0

In a Worker I need to yield regularly to allow the event loop to schedule incoming message processing.—At the moment I do that with a new promise and setTimeout().

addEventListener('message', () => console.log('reading incoming message'));
async function work() {
    while (true) {
        // do a piece of work
        await new Promise(resolve => setTimeout(resolve, 0));
        // break if ordered via message
    }
}
work();

Is there a compacter way to voluntarily yield processing?—It feels as if I’m missing something here: it looks like a super common task to do, but there is no “natural” way to do it?

Robert Siemer
  • 32,405
  • 11
  • 84
  • 94
  • Similar code as above, but await/promise split for less delay for re-entry, in case that is important: https://stackoverflow.com/a/62313956/825924 – Robert Siemer Jun 10 '20 at 22:52

1 Answers1

0

You could use generator functions, which are at least semantically clearer as to how the function behaves, but may not be "compacter" than your async function.
And to leave the control to the message queue, you can wait for an other message queue (i.e the one of a MessageChannel), which would be faster than setTimeout.

Kaiido
  • 123,334
  • 13
  • 219
  • 285