This is a little example of chunking computational loops with generator functions to allow JS threads to remain mostly unblocked.
Some notes on this example:
- This example uses a time threshold for yielding back to the event loop but it could easily be a loop iterations threshold
- This also only yields the final product as a promise but could easily be a subscription
- We use a wrapping functional loop (
processChunk
) to allow queueing more work to the event loop, but inside of that I opt for awhile
loop because a direct recursive loop can easily exceed call stack size limits in timeboxed execution loops.
You can see a similar example with multiple available computations plugged into the React lifecycle: https://codepen.io/makakoa/pen/qBLONVb
Probably not for most cases. Since this doesn't utilize separate threads there is non-zero impact to the parent thread. But some potential benefits are not relying on service worker support, being able to run parallel computations, and just living a little closer to whatever might be interested in the results.