#文章 js分解长任务的方法
以下是文章中提到的几种方案:
1.
setTimeout()+递归
通过递归调用
setTimeout(),将任务拆分成多个事件循环的tick,避免长时间阻塞主线程。
2.异步/等待+定时器
利用
async/await结合
setTimeout(),简化任务拆分逻辑,避免递归,代码更简洁易读。
3.
scheduler.postTask()使用
Scheduler接口的
postTask()方法,以更高效和可控的方式调度任务,支持设置任务优先级。
4.
scheduler.yield()通过
Scheduler接口的
yield()方法,在任务执行过程中释放主线程,让浏览器有机会处理其他任务,保持响应性。
5.
requestAnimationFrame()利用
requestAnimationFrame()在浏览器重绘周期之前调度任务,适合与渲染相关的任务,但可能影响渲染性能。
6.
MessageChannel()通过
MessageChannel实现任务拆分,类似于零延迟的
setTimeout(),但实现较为复杂,适合对性能要求较高的场景。
7.Web Workers
将任务移至主线程之外的Web Workers中执行,完全避免阻塞主线程,适合可以离线处理的复杂任务。
https://macarthur.me/posts/long-tasks/
Alex MacArthur
There are a lot of ways to break up long tasks in JavaScript.
It's very common to intentionally break up long, expensive tasks over multiple ticks of the event loop. But there are sure are a lot of approaches to choose from. Let's explore them.