Created
September 12, 2023 13:55
-
-
Save intrnl/942b4a92048a2b51b932f7ddb376b38d 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
export type IdleCallback = () => void; | |
const queue: IdleCallback[] = []; | |
let running = false; | |
const runTasks = (deadline: IdleDeadline) => { | |
while (deadline.timeRemaining() > 0) { | |
const callback = queue.shift(); | |
if (!callback) { | |
break; | |
} | |
callback(); | |
} | |
if (queue.length > 0) { | |
requestIdleCallback(runTasks); | |
} else { | |
running = false; | |
} | |
}; | |
export const scheduleIdleTask = (task: IdleCallback) => { | |
queue.push(task); | |
if (!running) { | |
running = true; | |
requestIdleCallback(runTasks); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment