Last active
May 2, 2022 08:20
-
-
Save tedpan/4cddd809c51a312aa11dcd1d5202e669 to your computer and use it in GitHub Desktop.
时间切片
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 时间切片 generator fn实现 | |
// 包装器 | |
function timeSliceWrapper(task){ | |
if(typeof task !== 'function'){ | |
throw new Error('请输入生成器函数!') | |
} | |
const gen = task() | |
const sliceSize = 25 | |
return function next(){ | |
let start = performance.now() | |
let res = gen.next() | |
while(!res.done && performance.now() - start < sliceSize){ | |
res = gen.next() | |
} | |
if(res.done){ | |
return res | |
}else{ | |
// 使用RIC延迟执行 | |
requestIdleCallback(next) | |
} | |
} | |
} | |
// 使用genrator函数拆分任务 | |
function *task(){ | |
let i = 0 | |
while(i < 10000){ | |
yield subTask(i) | |
i++ | |
} | |
} | |
// subTask | |
function subTask(i){ | |
// computed ... | |
let item = document.createElement("div") | |
item.innerText = `第${i++}条` | |
document.body.appendChild(item) | |
} | |
// 执行 | |
function excuteTask(){ | |
return timeSliceWrapper(task)() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment