Skip to content

Instantly share code, notes, and snippets.

@intrnl
Created September 12, 2023 13:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save intrnl/942b4a92048a2b51b932f7ddb376b38d to your computer and use it in GitHub Desktop.
Save intrnl/942b4a92048a2b51b932f7ddb376b38d to your computer and use it in GitHub Desktop.
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