模拟
2024年03月06日
一、setTimeout
1.1 认识
使用setTimeout
模拟相对简单,但精度较低,因为setTimeout
的调度并不保证精确。这种方法周期性检查是否有足够的空闲时间来执行回调(通常以50
毫秒为阈值),如果超时,那么无论如何都会执行该回调。
1.2 实现
function requestIdleCallbackOfSetTimeout() {
return (cb, { timeout } = {}) => {
const start = performance.now();
const callbackWrapper = () => {
const now = performance.now();
const didTimeout = timeout && now - start >= timeout;
if (didTimeout || now - start < 50) {
cb({
didTimeout,
timeRemaining() { return Math.max(0, 50 - (now - start)); },
});
} else {
window.setTimeout(callbackWrapper);
}
};
window.setTimeout(callbackWrapper);
};
}