JavaScript 中的分时函数可以用于将一个大任务分成多个小任务,每次只执行一小部分任务,从而避免阻塞浏览器
有时候,我们可能会在短时间内向页面中添加大量的节点,这样会让浏览器吃不消,导致浏览器卡顿甚至假死
事实上,网页动画的每一帧(frame)都是一次重新渲染。每秒低于24帧的动画,人眼就能感受到停顿。一般的网页动画,需要达到每秒30帧到60帧的频率,才能比较流畅。如果能达到每秒70帧甚至80帧,就会极其流畅。大多数显示器的刷新频率是60Hz,为了与系统一致,以及节省电力,浏览器会自动按照这个频率,刷新动画(如果可以做到的话)。所以,如果网页动画能够做到每秒60帧,就会跟显示器同步刷新,达到最佳的视觉效果。这意味着,一秒之内进行60次重新渲染,每次重新渲染的时间不能超过16.67毫秒
第一种方案
<body>
<a href="javascript:;" class="btn">按钮</a>
</body>
<script>
const ary = [];
Array.from({length: 100000}).forEach((i, index) => ary.push(index));
const btn = document.querySelector('.btn');
btn.onclick = function () {
// 创建 dom 节点并插入到 body 中
const createEle = text => {
const div = document.createElement('div');
div.textContent = text;
document.body.appendChild(div);
}
timeChunk(ary, createEle, 15000, 16);
}
/**
* 分时函数
* @param {Array} ary 遍历渲染的数组
* @param {Function} fn 数组每一项的回调函数
* @param {Number} count 一个时间片段内遍历数组多少项
* @param {Number} time 时间片段
* @returns {Function} 返回一个函数,形成闭包
*/
function timeChunk(ary, fn, count, time = 100) {
let t = null;
// 根据 count 将 ary 中的每一项依次取出执行 fn,直至 ary 长度为 0
const start = function() {
for (var i = 0; i < Math.min(count || 1, ary.length); i++) {
const aryItem = ary.shift();
fn(aryItem);
}
}
// 形成一个闭包
return function() {
const timeStart = Date.now();
// time 毫秒执行一下 start 函数,直至 ary 长度为 0,清除定时器 t
t = setInterval(function() {
if (ary.length === 0) {
const timeEnd = Date.now();
console.log('分时函数耗时 ', timeEnd - timeStart);
return clearInterval(t);
}
start();
}, time)
}
}
</script>
第二种方案
<body>
<a href="javascript:;" class="btn">按钮</a>
</body>
<script>
const datas = new Array(100000).fill(0).map((item, index) => index);
const btn = document.querySelector('.btn');
btn.onclick = function () {
const consumer = (data, index) => {
const div = document.createElement('div');
div.textContent = index;
document.body.appendChild(div);
};
const chunkSplitor = task => {
setTimeout(() => {
task(time => time < 16);
}, 30);
};
performChunk(datas, consumer, chunkSplitor);
};
function performChunk(datas, consumer, chunkSplitor) {
if (typeof datas === 'number') datas = new Array(datas);
if (!datas.length) return;
if (!chunkSplitor && globalThis.requestIdleCallback) {
chunkSplitor = task => {
requestIdleCallback(idle => {
task(() => idle.timeRemaining() > 0);
});
};
}
let i = 0; // 目前应该取出的任务下标
// 执行一块任务
function _run() {
if (i === datas.length) return;
chunkSplitor(hasTime => {
const now = Date.now();
while (hasTime(Date.now() - now) && i < datas.length) {
// 在这一帧还有空闲时间,且任务还没执行完
consumer(datas[i], i);
i++;
}
_run();
});
}
_run();
}
</script>
网友评论