任务数据量处理卡顿问题
任务分批次
为避免阻塞,可以将 长时间的单一任务 拆分成多个小任务并分批执行。这样可以在两次任务之间让浏览器有时间处理渲染、用户输入等操作。两种常见方法:
-
setTimeout
方法:- 使用
setTimeout
将任务分段,每段任务执行完毕后,通过定时器在稍后执行下一段。 - 例如:计算一个大型数组的和时,将数组分块,每次计算一部分,延迟剩余部分。
- 使用
-
requestAnimationFrame
方法:- 更适合与页面绘制相关的任务。
- 它会在每次浏览器刷新帧(通常是 16.67 毫秒,60 FPS)时调用指定的回调函数。
- 确保在每次任务之间,浏览器有机会完成页面渲染。
例子
// 用 setTimeout 拆分长任务
function performTaskInChunks(task, chunkSize) {
let index = 0;
function processChunk() {
const end = Math.min(index + chunkSize, task.length);
for (; index < end; index++) {
// 执行任务的每一小部分
console.log(`Processing: ${task[index]}`);
}
if (index < task.length) {
setTimeout(processChunk, 0); // 等待主线程空闲后继续
}
}
processChunk();
}
// 用 requestAnimationFrame 分布任务
function performTaskWithRAF(task) {
let index = 0;
function processFrame() {
if (index < task.length) {
console.log(`Processing: ${task[index]}`);
index++;
requestAni