Skip to content

Instantly share code, notes, and snippets.

@tedpan
Last active May 2, 2022 08:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tedpan/4cddd809c51a312aa11dcd1d5202e669 to your computer and use it in GitHub Desktop.
Save tedpan/4cddd809c51a312aa11dcd1d5202e669 to your computer and use it in GitHub Desktop.
时间切片
// 时间切片 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