Last active
November 13, 2019 08:49
-
-
Save azl397985856/517d13068923e8b706418b7d09ca8213 to your computer and use it in GitHub Desktop.
异步分段加载(可以用于性能优化)
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
/** | |
* | |
* @param size 分段的大小 | |
* @param arr 需要被处理的数组 | |
*/ | |
function chunk<T>(size: number, arr: Array<T>): Array<Array<T>> { | |
return Array.from({ length: Math.ceil(arr.length / size) }, (_, i) => | |
arr.slice(i * size, i * size + size) | |
); | |
} | |
/** | |
* | |
* @param config 配置,具体含义见行内注释 | |
* @param arr 需要被处理的数组 | |
*/ | |
export function trunckAsync<T>( | |
{ | |
gap, // 每一个异步结果在前一个异步多久之后排队执行 | |
size, // 分段大小 | |
}: { | |
gap: number; | |
size: number; | |
}, | |
arr: Array<T> | |
): Array< | |
Promise<{ | |
data: Array<T>; | |
i: number; | |
}> | |
> { | |
return chunk(size, arr).map((c, i) => { | |
return new Promise(r => { | |
setTimeout( | |
() => | |
r({ | |
data: c, | |
i, | |
}), | |
gap * i | |
); | |
}); | |
}); | |
} |
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
// 假设它很大,我们需要把它渲染到vue的template, 一次渲染会很卡 | |
const temp = this.veryBigArr = [1,2,3,4,5,6,7,8]; | |
this.veryBigArr = [] | |
// 每隔两秒渲染一个,直到全部渲染完成 | |
trunckAsync({size: 1, gap: 2000}, temp).map(p => { | |
return p.then(({ data: c, i }) => { | |
c.forEach((_, index) => { | |
this.veryBigArr[i + index] = c[index] | |
}) | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment