Skip to content

Commit

Permalink
Optimize idle scheduling (#2349)
Browse files Browse the repository at this point in the history
* Optimize idle scheduling

* updates

* fix lint

* updates
  • Loading branch information
deyihu authored Jun 21, 2024
1 parent ddd256b commit 2943ec4
Showing 1 changed file with 31 additions and 32 deletions.
63 changes: 31 additions & 32 deletions src/core/MicroTask.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,38 +102,38 @@ function loop() {
});
}

let loopFrameTime = now();
function frameLoop(deadline) {
const { idleTimeRemaining, idleLog, idleTimeout, idleForceTimeThreshold, idleEnable } = GlobalConfig;
if (Browser.requestIdleCallback && idleEnable) {
if (deadline && deadline.timeRemaining) {
const t = deadline.timeRemaining();
if (t > idleTimeRemaining || deadline.didTimeout) {
if (deadline.didTimeout && idleLog) {
console.error('idle timeout in', idleTimeout);
}
loop();
loopFrameTime = now();
} else {
const time = now();
if (time - loopFrameTime > idleForceTimeThreshold) {
loop();
loopFrameTime = now();
}
if (t <= idleTimeRemaining && idleLog) {
console.warn('currrent page is busy,the timeRemaining is', t);
}
let idleCallTime = now();
function idleFrameLoop(deadline) {
const { idleTimeRemaining, idleLog } = GlobalConfig;
if (deadline && deadline.timeRemaining) {
const t = deadline.timeRemaining();
if (t >= idleTimeRemaining) {
loop();
idleCallTime = now();
} else {
if (t < idleTimeRemaining && idleLog) {
console.warn('currrent page is busy,the timeRemaining is', t);
}
}
}
requestIdleCallback(idleFrameLoop);
}

function animFrameLoop() {
if (Browser.requestIdleCallback) {
const { idleForceTimeThreshold, idleLog } = GlobalConfig;
const time = now();
if (time - idleCallTime > idleForceTimeThreshold) {
loop();
idleCallTime = now();
if (idleLog) {
console.warn(`did not apply for availability, forced run idle`);
}
}
requestIdleCallback(frameLoop, { timeout: idleTimeout });
} else {
loop();
// Fallback to requestAnimFrame
requestAnimFrame(frameLoop);
if (idleLog) {
console.warn('current env not support requestIdleCallback. Fallback to requestAnimFrame');
}
}
requestAnimFrame(animFrameLoop);
}

let started = false;
Expand All @@ -142,12 +142,11 @@ export function startTasks() {
return;
}
started = true;
const { idleTimeout, idleEnable } = GlobalConfig;
if (Browser.requestIdleCallback && idleEnable) {
requestIdleCallback(frameLoop, { timeout: idleTimeout });
} else {
requestAnimFrame(frameLoop);
if (Browser.requestIdleCallback) {
requestIdleCallback(idleFrameLoop);
}
//always run requestAnimFrame
requestAnimFrame(animFrameLoop);
}

export function pushLoopHook(func) {
Expand Down

0 comments on commit 2943ec4

Please sign in to comment.