Get the latest tech news
Breaking Up with Long Tasks or: how I learned to group loops and wield the yield
Everything, On the Main Thread, All at Once Arrays are in every web developer's toolbox, and there are a dozen ways to iterate over them. Choose wrong, though, and all of that processing time will happen synchronously in one long, blocking task. The thing is, the most natural ways are the wrong ways
The key to breaking up the long task is to use the repetition to your advantage: each iteration of the loop is an opportunity to interrupt the processing and update the UI as needed. Resetting the timeOfLastYield is good so that the first backgrounded batch can run for the full 500 ms. And even though we’re racing the promises, the timeout’s callback will fire anyway, so it’s helpful to clear it during the rAF. That way, if the user returns before the work is completed, the visibility state will be updated and the regular batching logic will kick back in.
Or read this on Hacker News