Created
August 18, 2019 06:07
-
-
Save linx4200/e97956f7e650aa6f40e87911b9089623 to your computer and use it in GitHub Desktop.
时间分片 Demo
This file contains hidden or 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
// https://juejin.im/post/5d33fd0f5188256e820c80d4 | |
function isFunction(func) { | |
return typeof func === 'function'; | |
} | |
function isArray(arr) { | |
return Array.isArray(arr); | |
} | |
function init({ sliceList, callback }) { | |
if (!isFunction(callback)) { | |
console.error('callback 为必传参数并为 function'); | |
return; | |
} | |
// 添加切片队列 | |
this.generator = this.sliceQueue({ | |
sliceList, | |
callback | |
}); | |
// 开始切片 | |
this.next(); | |
} | |
function* sliceQueue({ sliceList, callback }) { | |
let listOrNum = (isNum(sliceList) && sliceList) || (isArray(sliceList) && sliceList.length); | |
for (let i = 0; i < listOrNum; ++i) { | |
const start = performance.now(); | |
callback(i); | |
while (performance.now() - start < 16.7) { | |
yield; | |
} | |
} | |
} | |
function next() { | |
const { generator } = this; | |
const start = performance.now(); | |
let res = null; | |
do { | |
res = generator.next(); | |
} | |
while (!res.done && performance.now() - start < 16.7); | |
if (res.done) return; | |
raf(this.next.bind(this)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment