Breaking Up with Long Tasks or: how I learned to group loops and wield the yield
['About The Author']
Performance Calendar
Everything, On the Main Thread, All at OnceArrays are in every web developer’s toolbox, and there are a dozen ways to iterate over them.
It’s not currently supported in all browsers, so production-ready use cases will need a polyfill or fall back to setTimeout .
function handleClick() { items.reduce(async (promise, item) => { await promise; await scheduler.yield(); process(item); }, Promise.resolve()); }This approach passes a promise along from one iteration to the next, which we can await before processing the next item.
When it’s time to yield, before calling scheduler.yield , await a promise that resolves in a requestAnimationFrame callback.
Hopefully this was a useful overview of the “yield in a loop” problem and how I’d go about solving it.
['calendar'
'yield'
'items'
'web'
'scheduleryield'
'ms'
'long'
'item'
'work'
'await'
'performance'
'processing'
'timeoflastyield']