分时段函数设计思想
思想设计
跟随袁大师思想
- 参数归一化设计
- 高级函数设计
- 神奇的量子纠纷,有人能回答吗?
<button class="btn">添加</button>
/**
* description
* 分时段函数
*/
var btn = document.querySelector(".btn");
var datas = new Array(10e1).fill("").map((_, index) => index);
btn.onclick = () => {
const consoumer = (item, i) => {
var div = document.createElement("div");
div.textContent = item;
document.body.append(div);
};
const chunkSplitor = (task) => {
setTimeout(() => {
task((time) => time < 16);
}, 1000);
};
// 高阶函数拆分
// performChunk(datas, consoumer, chunkSplitor);
// performChunk(datas, consoumer);
performChunk(1e3, consoumer);
};
function performChunk(datas, consoumer, chunkSplitor) {
// 参数归一化
if (typeof datas === "number") {
datas = new Array(datas).fill("").map((_, index) => index + 1);
}
if (datas.length === 0) return;
if (!Array.isArray(datas)) return;
if (
typeof chunkSplitor !== "function" &&
globalThis.requestIdleCallback
) {
chunkSplitor = (task) => {
globalThis.requestIdleCallback((idle) => {
task(() => {
const time = idle.timeRemaining();
console.log(time) // 加上log执行不完,神奇的量子纠纷
return time > 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) {
consoumer(datas[i], i);
i++;
}
});
}
_run();
}